In this section, we will learn what the String split() method is and how to use it in JavaScript.
How to Split String in JavaScript: String split() Method
Sometimes in JavaScript we have a text content and need to split that text into sub-string values.
This is where we can use the split() method.
Basically, with the help of this method, we can split a text content into sub-string values and then store the result in an array.
Note: this method does not change the original string value.
JavaScript String split() Syntax
string.split(separator, limit)
String split() Method Parameters:
The method takes two arguments:
The first argument is the separator. For example, let’s say we have the string value “This is John Doe” and want to split it by the white space. So the white space here is the separator, and we set that as the first argument to this method.
The second argument is the number of splits! For example, if we want only the first 4 split as the result of using this method, then the second argument needs to be set to 4.
String split() Method Return Value:
The return value of this method is an array that contains the splitted values.
Example: Split a String in JavaScript
const id = "If you work hard, then dreams will come true"; const res = id.split(" "); console.log(res);
Output:
["If", "you", "work", "hard,", "then", "dreams", "will", "come", "true"]
In this example, we’ve used white-space as the split point for the target string.
Note: if we use an empty string as the separator, the string value will be splitted between each character.
Example: splitting string in JavaScript
const id = "If you work hard, then dreams will come true"; const res = id.split(""); console.log(res);
Output:
["I", "f", " ", "y", "o", "u", " ", "w", "o", "r", "k", " ", "h", "a", "r", "d", ",", " ", "t", "h", "e", "n", " ", "d", "r", "e", "a", "m", "s", " ", "w", "i", "l", "l", " ", "c", "o", "m", "e", " ", "t", "r", "u", "e"]
Example: removing spaces from a string
const id = "If you work hard, then dreams will come true"; const res = id.split(" "); console.log(res.join(""));
Note: read the JavaScript Array join() method for more information.
Example: JavaScript reverse String
const id = "If you work hard, then dreams will come true"; const res = id.split(" "); console.log(res.reverse().join(" "));
Note: check the JavaScript Array reverse() method for more information.
Example: JavaScript split string into array
const id = "If you work hard, then dreams will come true"; const res = id.split("o"); console.log(res);
Output:
[ "If y", "u w", "rk hard, then dreams will c", "me true" ]