How to check if string contains in javascript

By FoxLearn 8/28/2024 6:49:09 AM   64
In JavaScript, there are several methods to check if a string contains a specific substring.

Using includes() Method

The includes() method checks if one string is contained within another and returns true or false.

Syntax:

string.includes(subString, position)
  • subString: The substring to search for.
  • position (optional): The position in the string at which to start the search. Defaults to 0.

For example:

const str = "Hello, world!";
const substring = "world";

console.log(str.includes(substring)); // true
let string = "Hello, World";
let substring = "H";

console.log(string.includes(substring,0)); // true

You can use includes() for a straightforward check if a substring is present.

Using indexOf() Method

The indexOf() method returns the index of the first occurrence of the specified value, or -1 if it is not found.

Syntax:

string.indexOf(subString, index)
  • subString: The substring to search for.
  • index (optional): The position in the string to start the search. Defaults to 0.

For example:

const str = "Hello, world!";
const substring = "world";

console.log(str.indexOf(substring) !== -1); // true

You can use indexOf() if you need the position of the substring and handle older browser compatibility.

Using search() Method with Regular Expressions

The search() method searches a string for a match against a regular expression and returns the index of the match or -1 if not found.

Syntax:

string.search(regexp)

regexp: A regular expression to search for.

For example:

const str = "Hello, world!";
const pattern = /world/;

console.log(str.search(pattern) !== -1); // true

You can use search() with regular expressions for more complex search criteria.