String objects so that it’s possible to use
String methods and access properties even for primitive strings.
The string length method returns the number of characters of the String.
let text = "DevelopersCode"; let len = text.length; console.log(len);
concat() – It is used to join two or more Strings.
Below we have two different ways to combine two strings.
let text1 = "Developers" + " " + "Help"; let text2 = "Developers".concat(" ", "Help"); console.log(text2);
To convert a string into lowercase – toLowerCase() method we can use.
To convert a string into uppercase- toUpperCase() method we can use.
let text = "Developers Help"; let text1 = text.toUpperCase(); let text2 = text.toLowerCase(); console.log(text1); console.log(text2);
DEVELOPERS HELP developers help
(i) slice(start, end): There are two arguments i.e. start position and end position.
let text = "Welcome to my site"; let text1 = text.slice(7, 13); console.log(text1);
" to my "
(ii) substring(): It is similar to the slice() method, the only difference is if start or end index values are less than 0 then that is treated as 0 (zero).
let text = "Welcome to my site"; let text2 = str.substring(7, 13); console.log(text2);
" to my "
let text = "Please visit College"; console.log(text); let newText = text.replace("College", "School"); console.log(newText);
Please visit College Please visit School
The replace() method returns a new string with changes and It replaces only the first match.
The trim() method removes all the whitespaces from the start and end of the string.
let text = " Hello World! "; console.log(text); let text1 = text.trim(); console.log(text1);
" Hello World! " Hello World!
trimstart() – It removes spaces from the starting of the string.
trimend() – It removes spaces from the ending of the string.
charAt and charCodeAt methods
There are some methods to fetch character details from the String. If we need to extract characters from a string then we use these methods :
(i) charAt (position)
The position is the index value of the string.
let text = "HELLO WORLD"; let char = text.charAt(4); console.log(char);
(ii) charCodeAt (position)
The position specifies the index value of the string.
let text = "Hello World"; let char = text.charCodeAt(4); console.log(char);