Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Make includes() exact with numbers JS

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 ?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can use Regex for this to include multiple test as a single pattern:

/(^4|[^\d]+4)[^\d]+years.*/i

Explanation:

  1. (^4|[^\d]+4): Either string start with 4 or has a non-numeric character before it.
  2. [^\d]+: Followed by at least 1 non-numeric character.
  3. years: Followed by exact word years
  4. .*: Means you can have any characters after it or be at the end.
  5. /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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading