Explain split("") , split(" ") and split(" ") method in javascript
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:
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 usesplit("")
, 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.
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 usesplit(" ")
, it will split the string into an array like["Hello", "World"]
. It separates the string into words by using spaces as the delimiter.
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 usesplit(" ")
, 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"
Subscribe to my newsletter
Read articles from Sumit Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by