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>
)
}
}