X



Home>Tutorial>

How to Split String in JavaScript: JavaScript Split Method

Nuelson Penuel Wednesday, August 2, 2023 Javascript

JavaScript Split Method

In JavaScript, the split() method is used to split a string into an array of substrings based on a specified delimiter. It returns the array of substrings as the result. The syntax for the split() method is as follows:
string.split(separator, limit)
Here, `string` is the original string that we want to split.

JavaScript Split Method Parameters

The `separator` parameter: is used to specify the character or regular expression pattern at which the string should be split. It can be a single character, a string, or a regular expression. If the separator is omitted, the split() method will split the string at every character. The optional `limit` parameter: restricts the maximum number of elements that should be included in the resulting array. For example, if the limit is set to 2, the split() method will only generate an array with a maximum of 2 elements.

Example of JavaScript Split Method

Here's an example that demonstrates the usage of the split() method:
const sentence = "Hello, how are you today?";
const words = sentence.split(" ");
console.log(words);
In the above example, we have initialized a string variable `sentence` with the value "Hello, how are you today?". We then call the split() method on this string, specifying the space character (" ") as the separator. This means that the string will be split at every occurrence of a space character. The resulting array, `words`, will contain each word as an element. The output of the above code will be:
["Hello,", "how", "are", "you", "today?"]
As you can see, the split() method splits the sentence string at each space character and generates an array of individual words. The split() method is commonly used for parsing and manipulating strings in JavaScript. It can be used to split a string based on various delimiters, such as spaces, commas, or even regular expression patterns. By splitting a string into an array of substrings, we can access and manipulate each part individually.

| | Views(208)

See Demo | Download File


Add your comment. Indicate code using code tag


Words: 0 | Chars: 0 | Reading Duration: 0



Images Attachment




Emmason Integratded Services(2017-2024)
All Rights Reserved
Designed and Maintained By Emmason Integrated Services