One option is to use the String.prototype.search()
method. . If the return is -1
does not exist, otherwise it is because it exists. See:
var str1 = "O menino joao foi ao mercado";
var str2 = "joao fo";
function compare(str1, str2){
return (str1.search(str2)>0)? true : false;
}
console.log(compare(str1,str2)); //true
If you prefer too, another option would be to use regular expression. For this case, it will return false
or true
, so that string 2 can be anywhere in string 1 . See:
var str1 = "O menino joao foi ao mercado";
var str2 = "joao fo";
var rx = new RegExp(str2);
console.log(rx.test(str1)); //true
You also have String.prototype.includes()
:
var str1 = "O menino joao foi ao mercado";
var str2 = "joao fo";
console.log(str1.includes(str2)); // true
console.log(str1.includes("joac")); // false