0

There is a string, I want to test if the string has multiple words in it, one simple way is to use the loop and includes() method, but I wonder would it possible to use RegExp to check. it

for example, the string is 'we could accumulate it at the price below 4000' , I need to check if the string has a combination of the words 'accumulate', 'price', 'below'.

user824624
  • 7,077
  • 27
  • 106
  • 183

1 Answers1

1

You can use regex, see https://regex101.com/:

const regex = /accumulate.*price.*below/gm;
const str = `we could accumulate it at the price below 4000

we could do it at the price below 4000'`;
let m;

while ((m = regex.exec(str)) !== null) {
    // This is necessary to avoid infinite loops with zero-width matches
    if (m.index === regex.lastIndex) {
        regex.lastIndex++;
    }
    
    // The result can be accessed through the `m`-variable.
    m.forEach((match, groupIndex) => {
        console.log(`Found match, group ${groupIndex}: ${match}`);
    });
}
Dimitri Kopriwa
  • 13,139
  • 27
  • 98
  • 204