Javascript String split()

Introduction

Javascript String split() method separates the string into an array of substrings based on a separator.

str.split([separator[, limit]])
  • separator - Optional, the string to split. Can a string or a regular expression.
  • limit - Optional, limiting the number of pieces.

The separator may be a string or a RegExp object.

When the string is empty, split() returns an array containing one empty string.

const myString = ''
const splits = myString.split()//  w  w  w . ja  v  a2 s  . c o m
console.log(splits)

An optional second argument, the array limit, ensures that the returned array will be no larger than a certain size.


let colorText = "red,blue,green,yellow"; 
let c = colorText.split(",");       // ["red", "blue", "green", "yellow"] 
console.log(c);/*ww w.j  a  v a 2s.  co m*/
c = colorText.split(",", 2);    // ["red", "blue"] 
console.log(c);
c = colorText.split(/[^\,]+/);  // ["", ",", ",", ",", ""] 
console.log(c);

In the following example, split() looks for spaces in a string and returns the first 3 splits that it finds.

const myString = 'Hello World. How are you doing?'
const splits = myString.split(' ', 3)

console.log(splits)/*w w w  . j a  v a2 s .  c o  m*/

In this last call to split(), the returned array has an empty string before and after the commas.

This happens because the separator specified by the regular expression appears at the beginning of the string.

Splitting with a RegExp to include parts of the separator in the result

const myString = 'this is a 1 CSS 2 HTML 3 Java 4 5'
const splits = myString.split(/(\d)/)

console.log(splits)/*from   w ww.j a v  a  2s  . c om*/

Reversing a String using split()

const str = 'asdfghjkl'
const strReverse = str.split('').reverse().join('') 



PreviousNext

Related