JavaScript String split | Method

  • by

If you want to divide a String into an ordered list of substrings then use the JavaScript String split() Method. This method splits a string into an array of substrings and returns the new array.

str.split(separator, limit)
  • separator (optional) – The pattern describing where each split should occur.
  • limit (optional) – An integer that limits the number of splits.

Note: this method does not change the original string.

JavaScript String split

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <script>
    const str = 'JavsScript split() method.';

    const words = str.split(' ');
    console.log(words[1]);

    const chars = str.split('');
    console.log(chars[8]);
  </script>
</body>
</html> 

Output:

JavaScript String split Method

The split string between words

If (” “) is used as a separator in the split() method, the string is split between words.

console.log("ABCDEF".split("")); // [ 'A', 'B', 'C', 'D', 'E', 'F' ]

How do I split a string, breaking at a particular character?

Answer: With JavaScript’s String.prototype.split function:

var input = 'john smith~123 Street~Apt 4~New York~NY~12345';

var fields = input.split('~');

var name = fields[0];
var street = fields[1];
// etc.

Do comment if you have any doubts or suggestions regarding this JS split method 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.

This site uses Akismet to reduce spam. Learn how your comment data is processed.