In this tutorial, you will learn what is Javascript split string method and how to use it with the help of examples.
The Javascript split()
method is a string method that is used to break down a string into substrings and returns them as an array.
Also Read :
Javascript Split() Method
Example
str = "Welcome to Codingclaw";
//breakdowns the string from spaces
strArray = str.split(" ");
console.log(strArray);
//Output : [ 'Welcom', 'to', 'Codingclaw' ]
split() Method Syntax
Here is the syntax of the javascript split()
method:
string.split(separator, limit)
Here string
is any string on which you will apply this method.
split() Method Parameters
separator – This is the pattern (string or regular expression) that specifies where each split will occur (Optional).
limit – it is the non-negative number that specifies the limit of the substrings to be split from the string (Optional).
split() Method Return Value
It returns an array of substrings formed from the breakdown of the string.
Note: split()
method doesn’t change the original string.
Example 1: Using split() method
console.log("abcdef".split(""));
//Output : [ 'a', 'b', 'c', 'd', 'e', 'f' ]
str = "codingclaw.com is a blog. for programmers";
let pattern = ".";
let result1 = str.split(pattern);
console.log(result1);
//Output: [ 'codingclaw', 'com is a blog', ' for programmers' ]
let pattern1 = ".";
// only 2 substring will be split from the string
let result2 = str.split(pattern1, 2);
console.log(result2);
//Output: [ 'codingclaw', 'com is a blog' ]
const str2 = "javascript,rust,go,python";
let pattern2 = ",";
let result3 = str2.split(pattern2);
console.log(result3);
//Output: [ 'javascript', 'rust', 'go', 'python' ]
// using RegEx with split()
let pattern3 = /\s*(?:,|$)\s*/;
let result4 = str2.split(pattern3);
console.log(result4);
//Output: [ 'javascript', 'rust', 'go', 'python' ]
Output
[ 'a', 'b', 'c', 'd', 'e', 'f' ]
[ 'codingclaw', 'com is a blog', ' for programmers' ]
[ 'codingclaw', 'com is a blog' ]
[ 'javascript', 'rust', 'go', 'python' ]
[ 'javascript', 'rust', 'go', 'python' ]
So that was all about the Javascript split string method, Hope you understood the concept behind the split()
method. If still you have any queries left in your mind then please do ask in the comment section below.