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 string split js method variations, you’ll learn about in this post.

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.

General syntax of JavaScript split method

string.split(separator, limit)

Separator: It’s an optional parameter. It defines the character, or the regular expression. If you don’t provide the separator, it will return full string as an array.

Limit:It’s an optional parameter. 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.

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 separator and limit

var str2 = "example two of str split";

var re = str2.split(" ", 1);

console.log(re);

Result/Output  

["example"]

JavaScript split string by comma

The following example illustrates “how to split string by comma”.

 var myString = 'this,is,an,comma';

 var mySplits = myString.split(","); 

 console.log(mySplits);

Result/Output  

[ "this", "is", "an", "comma" ]

JavaScript split by slash using regular expression(regex)

we can split string by slash by applying regular expression.

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

 console.log(mySplits);
 


Result/Output  

[ "this", "is", "slash" ]

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)

we can split string by providing regular expression.

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 string uppercase

var myString = 'HelloLetsSplitString';
   
var mySplits = myString.split(/(?=[A-Z])/);

console.log(mySplits);
 
 
Result/Output  

 [ "Hello", "Lets", "Split", "String" ]

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

var arrayString = "Regular Expression";
   
var myArraySplits = arrayString.trim().split(" ");

console.log(myArraySplits);
 
Result/Output 

["Regular","Expression"]

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 string split js 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.

function myFunction(node) {

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(":")); //[["key","value"],["key","value"]]

const result = new Map(strvalue);

console.log(result.get("country") );

Note: const is available in ES6 standard.
Result/Output

"Finland"

Javascript split string reverse method

var result  = 'reversestring'.split('').reverse().join('') ;

console.log(result);

Result/Output

"gnirtsesrever"

Zavascript 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]

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