0

While matching for specific text in regex I want to traverse word by word rather than camparing whole string at once. I am currently using this piece of code:

function processData(input) {
    const regex= /our$||or$||our,$||our.$||or,$||or.$/;
    var a=0;
    if(regex.test(input))
    a=a+1;
    console.log(a);
} 

I want to break the string input into words and iterate over it (words by word). I checked split() function but no could not understand.

2 Answers2

1

Use split(' '); that will break into an array of words and iterate from there.

1

You can use match to split a string into an array of 'words'. Next you can use Array.filter to find the words with a certain condition. Something like:

const aStringWithWords = `Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum`;
const words = aStringWithWords.match(/\w+/g);
//                             ^ creates an Array of 'words'
const filteredWords = words.filter( word => /in/i.test(word) );
//                                          ^ words containing 'in'
console.log(filteredWords);
.as-console-wrapper { top: 0; max-height: 100% !important; }
KooiInc
  • 119,216
  • 31
  • 141
  • 177