2 gennaio 2015

How check if a substring is contained in another string in JavaScript

It's possibile use the function "indexOf" that returns the position of the string in the another string. If not found, it will return -1:
For example:
var s = "stringa";
alert(s.indexOf("ng") > -1);


Other way, it could be used jQuery's :contains selector.

Last way is the method String.includes():
For example:
var str = 'To be, or not to be, that is the question.';
console.log(str.includes('To be'));       // true
console.log(str.includes('question'));    // true
console.log(str.includes('nonexistent')); // false
console.log(str.includes('To be', 1));    // false
console.log(str.includes('TO BE'));       // false


Bye

Nessun commento: