How to Split a String in JavaScript

Javascript Jeep🚙💨
JavaScript in Plain English
2 min readDec 5, 2020

--

Understanding the Split Method in JavaScript

Image taken here.

The split method spilt the string into array of substring based on the pattern provided.

Example

let numbersStr = "1,2,3,4,5";let numArray = numbersStr.split(",");console.log(numArray); // ["1","2","3","4","5"]

In the above example , the split method will loop through all the character of the string , if the pattern provided is found then the split method will collect the characters looped before finding the pattern and join all the characters as a string and pushed that string into an array .

If we don’t pass any pattern then the entire string will be pushed to an array and returned

numbersStr.split(); // ["1,2,3,4,5"]; 

If the pattern passed is the first character of the string , then an empty stirng is pushed into the array .

numbersStr.split("1"); // ["", "2,3,4,5"]

Also if the pattern passed is the last character if string , then an empty string is pushed to the resultant array.

numbersStr.split("5")' // ["1,2,3,4", ""]

If we pass pattern as empty string the each character of the string is splitted and pushed into array

numbersStr.split("");
// ["1", ",", "2", ",", "3", ",", "4", ",", "5"]

We can also pass number of split operation to be done by passing the limit param.

numberStr.split(",", 2); // ["1", "2"]

If we pass limit as 0 then an empty string will be returned

numberStr.split(",", 0); // []

Real world Example .

  1. Getting the value from css property in JavaScript .
let divHeight = document.getElementById("div1").style.height; //10pxlet height = divHeight.split("px");console.log(height); // "10"

2. Reversing a string

let name = "test";let splittedArray = name.split(""); // ["t", "e", "s", "t"]splittedArray.reverse(); // ["t", "s", "e", "t"]let reversedString = splittedArray.join(""); // tset

Thank you for reading. If you found this useful, please consider donating to me via PayPal.

--

--