JavaScript String Methods
String Methods | String Methods |
---|---|
String length | String slice() |
String substring() | String substr() |
String replace() | String replaceAll() |
String toLowerCase() | String concat() |
String trim() | String trimStart() |
String trimEnd() | String padStart() |
String padEnd() | String charAt() |
String charCodeAt() | String split() |
Note
String search methods are covered in the next chapter.
JavaScript String Length
The length property returns the length of a string:
Example
Edit it yourselflet text = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
let length = text.length;
Extracting String Parts
There are 3 methods for extracting a part of a string:
slice(start, end)
substring(start, end)
substr(start, length)
JavaScript String slice()
slice() extracts a part of a string and returns the extracted part in a new string.
The method takes 2 parameters: start position, and end position (end not included).
Example
Edit it yourselfSlice out a portion of a string from position 7 to position 13:
let text = "Apple, mango, orange";
let part = text.slice(7, 13);
Note
JavaScript counts positions from zero.
First position is 0.
Second position is 1.
Example
Edit it yourselfIf you omit the second parameter, the method will slice out the rest of the string:
let text = "Apple, mango, orange";
let part = text.slice(7);
Example
Edit it yourselfIf a parameter is negative, the position is counted from the end of the string
let text = "Apple, Banana, Kiwi";
let part = text.slice(-12);
Example
Edit it yourselfThis example slices out a portion of a string from position -12 to position -6:
let text = "Apple, Banana, Kiwi";
let part = text.slice(-12, -6);
JavaScript String substring()
substring() is similar to slice().
The difference is that start and end values less than 0 are treated as 0 in substring().
Example
Edit it yourselflet str = "Apple, Banana, Kiwi";
let part = str.substring(7, 13);
If you omit the second parameter, substring() will slice out the rest of the string.
JavaScript String substr()
substr() is similar to slice().
The difference is that the second parameter specifies the length of the extracted part.
Example
Edit it yourselflet str = "Apple, Banana, Kiwi";
let part = str.substr(7, 6);
If you omit the second parameter, substr() will slice out the rest of the string.
Example
Edit it yourselflet str = "Apple, Banana, Kiwi";
let part = str.substr(7);
If the first parameter is negative, the position counts from the end of the string.
Example
Edit it yourselflet str = "Apple, Banana, Kiwi";
let part = str.substr(-4);