Javascript split string method splits a string object to an array of strings by breaking up the string into substrings.

wondering how to split the string in javascript? Here are the split js string methods, you’ll learn about in this post. Also this is pretty much similar to Java split.

What is JavaScript split method?

The JavaScript split() method splits a string object to an array of strings by breaking up the string into substrings.

  • split method is used to split a string into an array of sub strings.
  • split method returns new array.
  • split method doesn’t change the original string.

Syntax of JavaScript split method

string.split(seperator, limit)

Seperator and Limit are two arguments that a split method can accept.
Seperator: It’s an optional argument. It defines the character, or the regular expression. If you don’t provide the seperator character, it will return full string as an array.

Limit:It’s an optional argument. It defines how many times to split a matched value. If limit is not specified, it will split at all matched values and return array.
Note: In separator, If an empty string (“”) is used, then the string is split between each character.

There are number of ways to split a string, so we are trying to cover different string methods implementation below.

JavaScript split string by whitespace


var str = "Welcome To My Blog";
var re = str.split(" ");
console.log(re);

Result/Output  
["Welcome", "To", "My", "Blog"];

split js by seperator character and limit

var str2 = "example two of character class";
var re = str2.split(" ", 1);
console.log(re);

Result/Output
["example"]

JavaScript split string by comma(CSV)

The following example illustrates “How to split comma separated string using javascript”. Refer to string input and output.


 var myString = 'this,is,an,csv file';
 var mySplits = myString.split(","); 
 console.log(mySplits);

Result/Output
[ "this", "is", "an", "csv file" ]

JavaScript split by slash using regular expression(regex) pattern

we can split string by slash by applying regular expression pattern. Refer to the below string input and output.


var myString = 'this/is/slash';
var mySplits = myString.split(/[\\\/]/); 
console.log(mySplits);

Result/Output  
[ "this", "is", "slash" ]

Similary viceversa incase you want to split using backslash.

Split string at index

Following JavaScript split function example illustrates “how to split string at index”.


function splitIndex(value, index) {
return value.substring(0, index) + "," +value.substring(index);
}
var result = splitIndex("3362174", 3);
console.log(result);

Result/Output 
[336,2174]

JavaScript split regex(regular expression) pattern

we can split string by providing regular expression pattern.


var date = "04-29-2017";
var mySplits = date.split(/[.,\/ -]/);
console.log(mySplits);

Result/Output
[ "04", "29", "2017" ]

Split string by delimiters


var delimiter = "abcd+wxyz-ghi";
var separators = [' ', '\\\+', '-', '\\\(', '\\\)',
'\\*', '/', ':', '\\\?'];
console.log(separators.join('|'));
var result = 
 delimiter.split(new RegExp(separators.join('|'), 'g'));
console.log(result);

Result/Output
[ "abcd", "wxyz", "ghi" ]

JavaScript uppercase


var myString = 'HelloLetsSplitCharacterClass';
var mySplits = myString.split(/(?=[A-Z])/);
console.log(mySplits);
 
Result/Output
[ "Hello", "Lets", "Split", "Character", "Class" ]

JavaScript split length method


var myString = "prototype,str,split,method";
var mySplits = myString.split(',').length;
console.log(mySplits);
 
Result/Output
4

JavaScript split to get first element


var myString = "welcome_to_split function";
var mySplits = myString.split(/_(.+)/)[0];
console.log(mySplits);

Result/Output
welcome

The result/output can be seen by using JavaScript console log method or document write method.

JavaScript split string into array

split() function splits a string into an array of strings by breaking up the string into substrings.


var arrayString = "Regular Expression";
var myArraySplits = arrayString.trim().split(" ");
console.log(myArraySplits);
 
Result/Output 
[Regular,Expression]

If you are looking to parse JSON string into an array, following example illustrates that.


var fullData ='{"fname":"Thomas","lname":"Cook","city":"Miami",
"state":"Florida", "Hobbies":"golf,trading,chess,fishing"}';
var data = JSON.parse(fullData);
var getHobbies = data.Hobbies;
var getHobbiesArray = getHobbies.split(",");
console.log(getHobbiesArray);
 
Result/Output 
[golf,trading,chess,fishing]

Using split function, we can parse querystring as well.

Javascript split string into chunks


var myString = '0204161980';
var myChunkSplits = myString.match(/.{1,2}/g); 
console.log(myChunkSplits);

Result/Output  
["02", "04", "16", "19", "80"]

Converting string to a character array using split js string method


var myString = "Hello JavaScript Array!";
var myCharacterSplit = myString.split(''); 
console.log(myCharacterSplit);
 
Result/Output
["H", "e", "l", "l", "o", " ", "J", "a", 
"v", "a", "s", "c", "r","i", "p", "t"," ",
"A", "r", "r", "a","y","!"]

JavaScript get element by id and split

In JavaScript, you can get element by id and split. Here is the sample javascript split function.


var myString = document.getElementById('node').value.trim( );
var myElementSplit = myString.split(/\s+/); 
console.log(myElementSplit);

Split string on a given index and return the values using string split js method

The following javascript split function illustrates, how to split string on specified index and return the values by using string split js method.


function splitString(value, index) {
return value.substring(0, index)+ "," +value.substring(index);
}
console.log(splitString("0123456", 2));

Result/Output
[01,23456]

Receiving error JavaScript split is not a function?

You might be experiencing error “TypeError: string.split is not a function” , This happens whenever you are calling .split() method on other than a string, the JS runtime won’t find the .split() method for that data type. for such scenarios, you must ensure to pass a string to your function.

Here is an example:


var test = Hello Javascript;
result = test.split(" ");
console.log(result);

The above JavaScript snippet will throw an error “TypeError: string.split is not a function”, since here we are trying to split the variable test ( Hello Javascript) which is not a string type.

The correct declaration of this split function should be as follows


var test = "Hello Javascript";
result = test.split(" ");
console.log(result);

So here we declared variable test as string (added string quotes “” to Hello Javascript), The result will be [Hello,Javascript]

Javascript split on newline

The following example will return array of strings upon using js split() method to split on newline.


var arraytest = "cat\nrat";
result = arraytest.split("\n");
console.log(result);

Result/Output
["cat", "rat"] 

JavaScript split string to map method(using ES6 standard)


const string = "country:Finland, city:Helsiniki,";
const strvalue = string.split(",").map(pair=>pair.split(":"));
const result = new Map(strvalue);
console.log(result.get("country") );

Note: const is available in ES6 standard.

Result/Output
["Finland"]

Javascript reverse string


var result  = 'reversestring'.split('').reverse().join('') ;
console.log(result);
Result/Output
["gnirtsesrever"]

Javascript split join method


var emailstr = "[email protected]_com,[email protected]_com";
var emailarray = emailstr.split('_');
var result = emailarray.join('.');
console.log(result);

Result/Output
[[email protected],[email protected]]

Javascript split string on quotation marks


var text = "I would \"like\" to \"split string\".";
var result = text.split("\"");
console.log(result);
Result/Output
[I would ,like, to ,split a string,.]

Javascript split string on special character


var text = "[email protected]_special.character";
var result = text.split(/[.\@_]/);
console.log(result);
Result/Output
[i,like,special,character]

Want to deep dive into JavaScript programming history, you can check this outstanding JavaScript wiki.

Check out more Javascript methods like Javascript substring().

Pin It on Pinterest

Share This