Skip to content

JavaScript split a string into array by comma | Example code

  • by

Use the split() method on the string and pass a comma as a parameter to split a string into an array by comma in JavaScript. This method divides the string on each comma and returns the substrings in an array.

var array = string.split(',');

MDN reference, is mostly helpful for the possibly unexpected behavior of the limit parameter. (Hint: "a,b,c".split(",", 2) comes out to ["a", "b"], not ["a", "b,c"].)

JavaScript splits a string into arrays by comma

A simple example code converts a Comma Separated String to an Array.

<!DOCTYPE html>
<html>
<head>
  <body>
    <script>

      var names = 'Harry,John,Clark,Peter,Rohn,Alice';
      var nameArr = names.split(',');
      console.log(nameArr);

      // Accessing individual values
      console.log(nameArr[0]); // Harry
      console.log(nameArr[1]); // John
      console.log(nameArr[nameArr.length - 1]); // Alice

      var str = 'Hello World!';
      var chars = str.split('');
      console.log(chars);

      // Accessing individual values
      console.log(chars[0]); // H
      console.log(chars[1]); // e
      console.log(chars[chars.length - 1]); // !

  </script>

</body>
</html>

Output:

JavaScript split a string into array by comma

Do comment if you have any doubts or suggestions on this Js split topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

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