JavaScript Split String By Comma into Array

Convert comma separated string to array in javaScript; Through this tutorial, i am going to show you how to split string by comma, index, slash, newline, hyphen, etc, in javascript.

JavaScript Split String By Comma into Array

Using the following ways to convert comma separated string to array in JavaScript; As follows:

  • String Split Without Separator
  • String Split With Separator
  • String Split With Separator and Limit
  • JavaScript Split String By Comma
  • String Split Separator at Beginning/End:
  • Javascript split regex

String Split Without Separator

Split string without any separator,you can see the following example:

var str = "Hello, This is js.";
var out = str.split();
console.log(out); //["Hello, This is js."]

String Split With Separator

Split string with separator, you can see the following example:

var str = "Hello, This is js.";
var out = str.split(" ");
console.log(out); // ["Hello,", "This", "is", "js."]

String Split With Separator and Limit

With limit and separator split a string, you can see the following example:

var str = "This is js";
var out = str.split(" ", 2);
console.log(out); // ["This", "is"]

JavaScript Split String By Comma

In javascript, split a string by comma. you can see the following example:

var str = "This, is, javascript, string ,split example";
var out = str.split(",");
console.log(out); // ["This", " is", " javascript", " string ", "split example"]

String Split Separator at Beginning/End:

If a separator is found at the beginning or end of a string, the first and last elements of the resulting array may be empty strings:

  var str = 'A|B|C|D|E|F|G|H|I|J|K|L|M|N|O|P|Q|R|S|T|U|V|W|X|Y|Z';
  var arr = str.split('|'); // using the empty string separator
  console.log( arr );
 
  //(26) ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"]

Javascript split regex

split string in javascript using regular expression pattern. You can see the following example:

var date = "2020-05-25";
var split = date.split(/[.,\/ -]/);
console.log(split); // ["2020", "05", "25"]

Conclusion

In this tutorial, you have learned how to split string in javascript with different ways.

More JavaScript Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *