javascript search code example
Example 1: js string search
var str = "This is a test sentence";
var hasTest = str.includes("test");
if(hasTest == true){
}
Example 2: function search in javascript array
function findInArray(ar, val) {
for (var i = 0,len = ar.length; i < len; i++) {
if ( ar[i] === val ) {
return i;
}
}
return -1;
}
var ar = ['Rudi', 'Morie', 'Halo', 'Miki', 'Mittens', 'Pumpkin'];
alert( findInArray(ar, 'Rudi') );
alert( findInArray(ar, 'Coco') );
Example 3: search in javascript
str.indexOf("locate");
str.lastIndexOf("locate");
str.indexOf("locate", 15);
str.search("locate");
Example 4: search in javascript
var str = "Please locate where 'locate' occurs!";
var ind1 = str.indexOf("locate");
var ind2 = str.lastIndexOf("locate");
var ind3 = str.indexOf("locate", 15);
var ind4 = str.search("locate");
document.write("<br>" + "Length of string:", len);
document.write("<br>" + "indexOf:", ind1);
document.write("<br>" + "index of last:", ind2);
document.write("<br>" + "indexOf with start point:", ind3);
document.write("<br>" + "search:", ind4);