The index number of any string starts from 0, and each character corresponds to an index number which means the first character of any string corresponds at index 0, the second character will correspond to the 1st index and the last character let’s say the ‘nth’ character will correspond at the ‘n-1’ index number.
Here, at index 0 we have a character “T”, at index 1 we have “H”, a blank space at index number 4, and at final index “20”, we have “Y”, which means it doesn’t matter whether it’s a blank space or an alphabet each character corresponds to an index.
We can utilize a method “indexOf()” to check the index number of a character. The indexOf() method returns the first occurrence of a character that appears multiple times:
console.log("The index of 'C' is " , string.indexOf("C"));
The output will return the index where ‘C’ is placed:
console.log("Searched character is ", "THIS IS NEW YORK CITY");
console.log("Searched character is ", "THIS IS NEW YORK CITY".charAt(6));
In this example we access a character that is placed at index 6 using both methods:
In the output we will show a character ‘S’ which is located at index 6:
console.log("Break the string from whitespaces ", string.split(" "));
The whole string will be split from whitespaces:
As a result, we will get an array of 5 elements:
Now, we can access each element of the array with its index.
console.log("Convert the string into Lower Case : ", string.toLowerCase());
In this code, we utilize “toLowerCase()” method which will convert each character of the string into a lower case. The resultant output will be:
console.log("Convert the string into Upper Case : ", string.toUpperCase());
The above-given code will provide the following output:
We can replace a substring of any string using “replace()” method:
console.log("Convert the string into Upper Case : ", string.replace("this is" , "welcome to"));
In this code, we want to replace “this is” with “welcome to”, the output of the above-given code will be:
let string2 = " yes it is!!";
console.log("Combine string1 and string2 : ", string1.concat(string2));
We have two strings string1 and string2 we can combine these two using the “concat()” method as:
The output will display a concatenated string: