Explain split("") , split(" ") and split(" ") method in javascript

Sumit SinghSumit Singh
2 min read

The split() method in JavaScript is used to split a string into an array of substrings based on a specified separator. Let me explain the three cases you mentioned:

  1. split(""):

    • When you use an empty string "" as the separator, it means that you want to split the string into individual characters.

    • For example, if you have the string "Hello", and you use split(""), it will split the string into an array like ["H", "e", "l", "l", "o"]. Each character in the original string becomes a separate element in the resulting array.

  2. split(" "):

    • When you use a space character " " as the separator, it will split the string into an array of substrings based on spaces.

    • For example, if you have the string "Hello World", and you use split(" "), it will split the string into an array like ["Hello", "World"]. It separates the string into words by using spaces as the delimiter.

  3. split(" "):

    • When you use multiple space characters " " as the separator, it will split the string into an array of substrings based on those sequences of spaces.

    • For example, if you have the string "Hello World", and you use split(" "), it will split the string into an array like ["Hello", "World"]. It splits the string into words, considering three consecutive spaces as the delimiter.

In each case, the split() method is used to segment the original string based on the specified separator, and the result is an array containing the substrings.

const input = "You are winner!";
 const Output = input.split("").reverse().join("").split(" ").reverse().join(" "); 
console.log(Output); 

// Input:"You are winner!"
// Output: "uoY era !renniw"
0
Subscribe to my newsletter

Read articles from Sumit Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Sumit Singh
Sumit Singh