how to handle string in javascript

Solutions on MaxInterview for how to handle string in javascript by the best coders in the world

showing results for - "how to handle string in javascript"
Till
04 Nov 2019
1var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
2var str = "Please locate where 'locate' occurs!";
3var str1 = "Apple, Banana, Kiwi";
4var str2 = "Hello World!";
5
6var len = txt.length;
7
8var ind1 = str.indexOf("locate"); // return location of first find value
9var ind2 = str.lastIndexOf("locate"); // return location of last find value
10var ind3 = str.indexOf("locate", 15); // start search from location 15 and then take first find value
11var ind4 = str.search("locate");
12//The search() method cannot take a second start position argument. 
13//The indexOf() method cannot take powerful search values (regular expressions).
14
15var res1 = str1.slice(7, 13);
16var res2 = str1.slice(-12, -6);
17var res3 = str1.slice(7);
18var res4 = str1.slice(-12);
19var res5 = str1.substring(7, 13); //substring() cannot accept negative indexes like slice.
20var res6 = str1.substr(7, 9); // substr(start, length) is similar to slice(). second parameter of substr is length of string
21
22var res7 = str.replace("locate", "W3Schools"); //replace only replace first match from string
23var res8 = str.replace(/LOCATE/i, "W3Schools"); // i makes it case insensitive
24var res9 = str.replace(/LOCATE/g, "W3Schools"); // g replace all matches from string rather than replacing only first
25
26var res10 = str2.toUpperCase();
27var res11 = str2.toLowerCase();
28
29
30document.write("<br>" + "Length of string:", len);
31document.write("<br>" + "indexOf:", ind1);
32document.write("<br>" + "index of last:", ind2);
33document.write("<br>" + "indexOf with start point:", ind3);
34document.write("<br>" + "search:", ind4);
35document.write("<br>" + "slice:", res1);
36document.write("<br>" + "slice -ve pos:", res2);
37document.write("<br>" + "slice with only start pos:", res3);
38document.write("<br>" + "slice with only -ve start pos", res4);
39document.write("<br>" + "substring:", res5);
40document.write("<br>" + "substr:", res6);
41document.write("<br>" + "replace:", res7);
42document.write("<br>" + "replace with case insensitive:", res8);
43document.write("<br>" + "replace all:", res9);
44document.write("<br>" + "to upper case:", res10);
45document.write("<br>" + "to lower case:", res11);