how to handle string in javascript code example

Example: how to handle string in javascript

var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var str = "Please locate where 'locate' occurs!";
var str1 = "Apple, Banana, Kiwi";
var str2 = "Hello World!";

var len = txt.length;

var ind1 = str.indexOf("locate"); // return location of first find value
var ind2 = str.lastIndexOf("locate"); // return location of last find value
var ind3 = str.indexOf("locate", 15); // start search from location 15 and then take first find value
var ind4 = str.search("locate");
//The search() method cannot take a second start position argument. 
//The indexOf() method cannot take powerful search values (regular expressions).

var res1 = str1.slice(7, 13);
var res2 = str1.slice(-12, -6);
var res3 = str1.slice(7);
var res4 = str1.slice(-12);
var res5 = str1.substring(7, 13); //substring() cannot accept negative indexes like slice.
var res6 = str1.substr(7, 9); // substr(start, length) is similar to slice(). second parameter of substr is length of string

var res7 = str.replace("locate", "W3Schools"); //replace only replace first match from string
var res8 = str.replace(/LOCATE/i, "W3Schools"); // i makes it case insensitive
var res9 = str.replace(/LOCATE/g, "W3Schools"); // g replace all matches from string rather than replacing only first

var res10 = str2.toUpperCase();
var res11 = str2.toLowerCase();


document.write("
" + "Length of string:", len); document.write("
" + "indexOf:", ind1); document.write("
" + "index of last:", ind2); document.write("
" + "indexOf with start point:", ind3); document.write("
" + "search:", ind4); document.write("
" + "slice:", res1); document.write("
" + "slice -ve pos:", res2); document.write("
" + "slice with only start pos:", res3); document.write("
" + "slice with only -ve start pos", res4); document.write("
" + "substring:", res5); document.write("
" + "substr:", res6); document.write("
" + "replace:", res7); document.write("
" + "replace with case insensitive:", res8); document.write("
" + "replace all:", res9); document.write("
" + "to upper case:", res10); document.write("
" + "to lower case:", res11);

Tags:

Misc Example