String Manipulation with JavaScript
-
Split
Split transforms a string into an array of substrings based on given delimiter.
let str = "The dog jumped over the fence."; let substr = str.split(" "); console.log(substr); //["The", "dog", "jumped", "over", "the", "fence."]
split
can be given multiple delimiter using regular expression.let str = "I am counting my calories,yet I really want dessert."; let substr = str.split(/[" ",.]/); console.log(substr); //["I", "am", "counting", "my", "calories", "yet", "I", "really", "want", "dessert", ""]
-
Slice
It extracts a part of string between two given indices, the end index is exclusive.
let str = "The dog jumped over the fence"; let substr = str.slice(4,14); console.log(substr);//"dog jumped"
For negative index, the index starts from the end of string.
let str = "The dog jumped over the fence"; let substr = str.slice(-9); console.log(substr); //"the fence"
-
Replace
The replace method as the name implies replace a part of string with the specified string.
let str = "The dog jumped over the fence.The dog wagging its tail."; let substr = str.replace("dog","fox"); console.log(substr);//"The fox jumped over the fence.The dog wagging its tail."
In the above example, only the first “dog” has been replaced. To replace all “dog” in the sentence we have to use regular expression.
let str = "The dog jumped over the fence.The dog wagging its tail."; let substr = str.replace(/dog/g,"fox"); console.log(substr);//"The fox jumped over the fence.The fox wagging its tail."
-
indexOf
It searches for the occurrence of a value in a given string and returns the index where it is first found. If nothing is found, it returns -1.
let str = "The dog jumped over the fence"; let substr1 = str.indexOf("jumped"), substr2 = str.indexOf("cat") console.log(substr1," ",substr2);// 8 -1
-
trim
Removes all whitespaces from a string.
let str = " The dog jumped over the fence. "; let substr = str.trim(); console.log(substr); //"The dog jumped over the fence."
In addition, there are two other methods called
trimLeft()
andtrimRight()
which removes all leading whitespaces from the right side.