s

javascript check if string contains substring edit button Edit

author
Murugan Andezuthu Dharmaratnam | calendar 15 September 2020 | 2440

The below one line code is used to check if the string "hello world this is a test" contains a substring "world".

"hello world this is a test".includes("world")
returns : true
"hello world this is a test".includes("worldd")
returns : false
                    

the easiest way to run try code in javascript is to press ctrl shift i to open developer tools in chrome & copy-paste the code in the console tab.

until recently I was using the code below to check if a string contains another string

String.prototype.contains = function (it) { return this.indexOf(it) != -1; };
var str = "Hello world this is a test";
if(var.contains("world"))
{
   alert("It contains world");
}