Bootstrap FreeKB - Node.js - if string contains
Node.js - if string contains

Updated:   |  Node.js articles

This assumes you are familiar with if statements in Node.js. If not, check out my article Node.js - Getting Started with if else statements.

Here is an example with an if statement using includes.

const my_string = "Hello World";

console.log(my_string.toLowerCase());

if (my_string.toLowerCase().includes('hello')) {
  console.log("my_string includes hello");
} else {
  console.log("my_string does NOT include hello");
}

 

And here is an example using the test method. This has the advantage of being able to pass in a regular expression so that multiple strings can be matched.

const my_string = "Hello World";

if (/hello|world/.test(my_string.toLowerCase())) {
  console.log("my_string includes hello or world");
} else {
  console.log("my_string does NOT include hello or world");
}

 

Better yet, i can be used for a case insensitive match.

const my_string = "Hello World";

if (/hello|world/i.test(my_string)) {
  console.log("my_string includes hello or world");
} else {
  console.log("my_string does NOT include hello or world");
}



Did you find this article helpful?

If so, consider buying me a coffee over at Buy Me A Coffee



Comments


Add a Comment


Please enter cb5f3a in the box below so that we can be sure you are a human.