1var str = "This is a test sentence";
2var hasTest = str.includes("test");
3
4if(hasTest == true){
5 //do a thing
6}
1
2var str = "Please locate where 'locate' occurs!";
3
4var ind1 = str.indexOf("locate"); // return location of first value which founded
5var ind2 = str.lastIndexOf("locate"); // return location of last value which founded
6var ind3 = str.indexOf("locate", 15); // start search from location 15 and then take first value which founded
7var ind4 = str.search("locate");
8//The search() method cannot take a second start position argument.
9//The indexOf() method cannot take powerful search values (regular expressions).
10
11document.write("<br>" + "Length of string:", len);
12document.write("<br>" + "indexOf:", ind1);
13document.write("<br>" + "index of last:", ind2);
14document.write("<br>" + "indexOf with start point:", ind3);
15document.write("<br>" + "search:", ind4);
1// function to search array using for loop
2function findInArray(ar, val) {
3 for (var i = 0,len = ar.length; i < len; i++) {
4 if ( ar[i] === val ) { // strict equality test
5 return i;
6 }
7 }
8 return -1;
9}
10
11// example array
12var ar = ['Rudi', 'Morie', 'Halo', 'Miki', 'Mittens', 'Pumpkin'];
13// test the function
14alert( findInArray(ar, 'Rudi') ); // 0 (found at first element)
15alert( findInArray(ar, 'Coco') ); // -1 (not found)
16
1str.indexOf("locate"); // return location of first find value
2str.lastIndexOf("locate"); // return location of last find value
3str.indexOf("locate", 15); // start search from location 15 and then take first find value
4str.search("locate");
5//The search() method cannot take a second start position argument.
6//The indexOf() method cannot take powerful search values (regular expressions).
1/*
2 Arrays Methods [Search]
3 - indexOf(Search Element, From Index [Opt])
4 - lastIndexOf(Search Element, From Index [Opt])
5 - includes(valueToFind, fromIndex [Opt]) [ES7]
6*/
7
8let myFriends = ["Ahmed", "Mohamed", "Sayed", "Alaa", "Ahmed"];
9
10console.log(myFriends);
11
12console.log(myFriends.indexOf("Ahmed"));
13console.log(myFriends.indexOf("Ahmed", 2));
14
15console.log(myFriends.lastIndexOf("Ahmed"));
16console.log(myFriends.lastIndexOf("Ahmed", -2));
17
18console.log(myFriends.includes("Ahmed"));
19console.log(myFriends.includes("Ahmed", 2));
20
21if (myFriends.lastIndexOf("Osama") === -1) {
22 console.log("Not Found");
23}
24
25console.log(myFriends.indexOf("Osama"));
26console.log(myFriends.lastIndexOf("Osama"));