Strings are useful for holding data that can be represented in text form. Some of the most-used operations on strings are to check their length, to build and concatenate them using the + and += string operators, checking for the existence or location of substrings with the indexOf() method, or extracting substrings with the substring() method.
Finding the length of a string.
The length property is used to find the length of a string.
let str = 'phpforever'; console.log(str.length)
Output : 10
Finding a substring inside a string and extracting it.
The indexOf() method returns the index of (the position of) the first occurrence of a specified text in a string.
var str ="Find a string inside the string"; var pos = str.indexOf("string");
Output : 7
The lastIndexOf() method returns the index of the last occurrence of a specified text in a string.
var str = "Find a string inside the string"; var pos = str.lastIndexOf("string");
Output:25
Searching for a String in a String.
The search() method searches a string for a specified value and returns the position of the match.
var str = "Find a string inside the string"; var pos = str.search("string");
Output : 7.
Extracting String Parts.
There are 3 methods for extracting a part of a string.
- slice(start, end)
- substring(start, end)
- The slice() Method
The slice() Method.
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: the start position, and the end position (end not included).
Example.
var str = "Apple, Banana, Kiwi"; var res = str.slice(7, 13);
Output : Banana.
The substring() Method.
substring() is similar to slice(). The difference is that substring() cannot accept negative indexes.
var str = "Apple, Banana, Kiwi"; var res = str.substring(7, 13);
The substr() Method.
substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part.
str = "Please visit phpforever!"; var n = str.replace("phpforever", "forever");
Converting to Upper and Lower Case.
A string is converted to upper case with toUpperCase().
var text1 = "Hello World!"; var text2 = text1.toUpperCase();