Skip to content

split() String Method in JavaScript

In this short post we will see the use cases of split() method in JavaScript. The split() method separates an original string into an array of sub-strings, based on a separator string that you pass as input. The original string is not altered by split().


string.split(separator, limit)
  • separator – a string indicating where each split should occur. You can mention regular expression also as separator.
  • limit – a number for the amount of splits to be found

Simple Example

const str = "Hello! Poopcode. Welcome to learning!";
const splitStr = str.split("!");

// ["Hello", "Poopcode. Welcome to learning"]

Since we used the exclamation(!) as the separator string, the strings in the output array do not contain the exclamation in them – the output separated strings do not include the input separator itself.

You can operate on strings directly, without storing them as variables:

"Hello... I am a string... keep on learning!".split("..."); 
// [ "Hello", " I am a string", " keep on learning!" ]

Common Use Case

  • Create an array of words from a sentence
  • Create an array of letters in a word
  • Reversing the letters in a word
  • Splitting with a RegExp
const sentence = "Hai Poopcoder!";
// Split the sentence on each space between words - Case 1
console.log(sentence.split(" ")); // [ "Hai","Poopcoder!" ]

// Split the sentence on each letter - Case 2
// [ "H","a","i"," ","P","o","o","p","c","o","d","e","r","!" ]

// Split the sentence and reverse using the array methods. - Case 3
console.log(sentence.split("").reverse().join("")); // !redocpooP iaH

// Split with RegExp to include parts of the 
// separator in the result- Case 4
const myString = 'Hello 1 word. Sentence number 2.'
//[ "Hello ", "1", " word. Sentence number ", "2", "." ]

Browser Support

See also  Compare two dates in JavaScript using moment.js

Happy Learning 😀

Leave a Reply

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

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