
There could be cases where you may have passed a splitter that is not part of the string or doesn't match any part of it.

Usually, we use a splitter that is part of the string we are trying to split.

#CONVERT STRING TO ARRAY JAVASCRIPT HOW TO#
''.split() // returns How to Split a String Using a Non-matching Character Here are two examples so you can see the difference: // Returns an empty array let message = 'I am a Happy Go lucky Guy' Ĭonsole.log(message.split()) // returns 💡 Note again, calling the split() method on an empty string('') without a splitter will return an array with an empty string. When you invoke the split() method on a string without a splitter, it returns an array containing the entire string. This just means the split() method doesn't have any arguments passed to it. You can invoke the split() method on a string without a splitter/divider. You may get this as a question in your upcoming job interviews! ''.split('') // returns How to Split a String into One Array console.log(message.split('')) // 💡 Please note that splitting an empty string('') using an empty string as the splitter returns an empty array. The result of the split will be an array containing all the characters in the message string. In the example below, we split the same message using an empty string. You can split a string by each character using an empty string('') as the splitter. The main purpose of the split() method is to get the chunks you're interested in from a string to use them in any further use cases. Access each of the elements of the array. Split using a space characterĬonsole.log(arr) // Here the space character acts as a splitter or divider. Let's split the string based on the space ( ' ') character. We can call the split() method on the message string. Here is a string created using string literals: let message = 'I am a Happy Go lucky Guy' Let's understand how this works with an example. It doesn't make any modifications to the original string. The splitter can be a single character, another string, or a regular expression.Īfter splitting the string into multiple substrings, the split() method puts them in an array and returns it. The split() method splits (divides) a string into two or more substrings depending on a splitter (or divider). In this article will learn about a handy string method called split(). The image below represents the same thing: Accessing String Characters by the IndexĪpart from its ability to access string characters by their indices, JavaScript also provides plenty of utility methods to access characters, take out a part of a string, and manipulate it. So, we can access each of the characters of a string like this: let str = "Yes, You Can Do It!" The index of the first character is 0, and it increments by 1.


One interesting fact about strings in JavaScript is that we can access the characters in a string using its index.
