How to check if string contains substring in JavaScript

Channel: Linux
Abstract: Using search() Method You could also use the JavaScript search() method. It returns string position number if match found. If not match found returns

The JavaScript indexOf() method search for the substring in string and returns the position of the first occurrence of a specified substring. If substring not found, it returns -1. So you can use JavaScript IndexOf() method to check if a string contains substring in it. In this tutorial we will also provides example to use JavaScript includes() and search() methods to find substring in another string.

In a comparison of all 3 methods describes below, indexOf() can be better due to its speed of execution. If no speed matters, you can use any of the following methods.

Using indexOf() Method

JavaScript indexOf() method will return the starting position number substring in the main string. If substring not found, it will return -1 as a result.

var str = "Hello world"; var substr = "World"; var result = str.indexOf(substr) > -1; alert(result);1234var str = "Hello world";var substr = "World";var result = str.indexOf(substr) > -1;alert(result);

Result will be as below:

 true 
  • How to Append Element to Array in JavaScript
2. Using includes() Method:

Also you could use JavaScript includes() method. It returns true on match found and false if no match found. Use below sample code to test this:

var str = "Hello world"; var substr = "World"; var result = str.includes(substr) > -1; alert(result);1234var str = "Hello world";var substr = "World";var result = str.includes(substr) > -1;alert(result);

Result will be as below:

 true 
3: Using search() Method

You could also use the JavaScript search() method. It returns string position number if match found. If not match found returns -1.

var str = "Hello World"; var expr = "/World/"; var result = str.search(expr) > -1; alert(result);1234var str = "Hello World";var expr = "/World/";var result = str.search(expr) > -1;alert(result);

Result will be as below:

 true 
  • >How to Remove Array Element by Value in JavaScript

    Ref From: tecadmin

    Related articles