JavaScript split() method is used to split a string. This function is split a given string into an array of substrings and returns the new array.
It will use a separator and if no separator used then string (“”) is used as the separator. So the result is the string is split between each character.
Note: JS split() method doesn’t change the given string.
Syntax
string.split(separator, limit)
Parameter Values
- separator– Specifies the character to use for splitting the string, (Optional)
- limit– items after the split limit will not be included.
Return value
It returns an Array, containing the splitted values.
Examples of JavaScript split string
Let’ see the multiple example of js split string based on delimiter:-
1. Split string by space
Split string into an array of substrings using space as a separate in split method.
You can do same this for split string by comma in JavaScript.
str.split(",");
Example with space, try comma( or other delimiter or char) by yourself.
<!DOCTYPE html>
<html>
<head>
<script>
var str = "How are you doing today?";
var res = str.split(" ");
// Output in alert
alert(res)
</script>
</head>
</html>
Output:
2. Separate each character
If you will not pass any separator then it will use an empty string (“”) is used as the separator and split between each character including spaces.
<!DOCTYPE html>
<html>
<head>
<script>
var str = "EyeHunts";
var res = str.split("");
// Output in alert
alert(res)
</script>
</head>
</html>
Output:
3. Use the limit parameter in split() method
Setting a limit to 3.
<!DOCTYPE html>
<html>
<head>
<script>
var str = "How are you doing today?";
var res = str.split(" ", 3);
// Output in alert
alert(res)
</script>
</head>
</html>
Example JavaScript split regex
You can use regular expression for splitting, lets split date string in JS.
var date = "02-25-2010";
var myregexp2 = new RegExp("-.")
// Output in alert
alert(date.split(/[.,\/ -]/))
Output:
Q: How to Split string into two parts in JS?
Answer: Use indexof() method for it.
var someString = "A04.3 A new Code";
var index = someString.indexOf(" "); // Gets the first index where a space occours
var id = someString.substr(0, index); // Gets the first part
var text = someString.substr(index + 1); // Gets the text part
How to javascript split string at index?
Answer: Use JS slice() method, to spilt a string by index.
var str = "Hello world!";
var sb = str.slice(0, 5);
alert(sb);
Output and Read more Examples:- Slice method in JavaScript | Used Slice the String and Array
Do comment if you have any doubts and suggestion on this tutorial.
Note: The All JS Examples codes are tested on the Safari browser (Version 12.0.2) and Chrome.
OS: macOS 10.14 Mojave
Code: HTML 5 Version