How do I make it show me accuracy in includes() or maybe another way…
For example I do.
array.filter(item => {
if(item?.about?.toLowerCase()?.includes(
("4")) && item?.about?.toLowerCase()?.includes(
("years")
)
But in the text itself it is written, for example, "We have existed for 40 years".
It recognizes for me the number 4 within the 40 and then it filters it.
what can we do ?
>Solution :
You can use Regex for this to include multiple test as a single pattern:
/(^4|[^\d]+4)[^\d]+years.*/i
Explanation:
- (^4|[^\d]+4): Either string start with 4 or has a non-numeric character before it.
- [^\d]+: Followed by at least 1 non-numeric character.
- years: Followed by exact word years
- .*: Means you can have any characters after it or be at the end.
- /i: Means it will check case insensitively. So you do not have to do
.toLowerCase()const data = [ "We have existed for 40 years", "We have existed for 4 years", "We have existed for 44 years", "4 years at start", "4 is a random number in years" ] const output = data.filter((str) => { const regex = /(^4|[^\d]+4)[^\d]+years.*/i; return regex.test(str) }); console.log(output)