0

I have a search box and an array of items that I generate in filledArray and I'm trying to filter this array based on what is typed into the searchbox.

I am trying to get it to match the beginning of the word using a regex expression as with includes() it will match any character and doesn't give me the desired results.

How can I implement a regex expression that will match the searchTerm with the beginning of each item in my array of items and filter accordingly

class Task3 extends React.Component {
  state = {
    searchValue: '',
  }

  handleOnChange = (event) => {
    this.setState({ searchValue: event.target.value })
  }

  render() {
    const { addItem, itemsToShow, removeItem, selectedItems } = this.props
    const { searchValue } = this.state
    const filledArray = [...Array(301)].map((_, i) => `element ${i}`)
    return (
            <ElementsListWrap>
              {/* filter((item) => this.state.searchValue.includes(item)) */}
              {filledArray.slice(0, itemsToShow !== 'all' ? itemsToShow : filledArray.length)
              .filter((item) => new RegExp(`/^${searchValue}/`.test(item)))
              .map((index) => (
                <div
                  key={index} 
                  onClick={ () => { this.handleAddElement(index) } }>
                  <ElementWrap
                    active={selectedItems.includes(index)}>
                  {index}
                  </ElementWrap>
                </div>
                ),
              )}
            </ElementsListWrap>
    )
  }
}
tom harrison
  • 3,273
  • 11
  • 42
  • 71
  • 4
    ``new RegExp(`/^${searchValue}/`.test(item))`` => ``new RegExp(`^${searchValue}`).test(item)``. Note that the regex issue is that you included the regex delimiters into the pattern making the regex engine search for literal slashes in the text. The rest is a typo in the code. – Wiktor Stribiżew Jan 28 '20 at 10:53
  • .filter((item) => new RegExp(`^${searchValue}`).test(item)) worked for me – tom harrison Jan 28 '20 at 10:56

0 Answers0