/  Technology   /  JavaScript String split()

JavaScript String split()

 

The split() method in JavaScript splits a string into an array of substrings, places those substrings in an array, and returns the new array. The original string is not altered.

Instead of returning an empty array when the string is empty, the split() method returns an array containing an empty string. When both the string and separator are empty, the empty array is returned.

Syntax

string.split(separator, limit)  

separator: This parameter is optional. A regular expression or a simple string can be used. This specifies the point at which the split should occur.

The sequence of the entire character must be found if there are multiple characters.

In the absence of the separator, or if it is omitted, the entire string becomes a single element of the array. As a result, the returned array contains a single element containing the entire string.

It is still possible to split the string if the separator appears at the beginning or the end of the string. An empty string of zero length appears at the beginning or the end of the returned array.

limit: This parameter is also optional. The number of limits is a non-negative integer. This parameter specifies the maximum number of splits that may be found in the given string. It splits the string at each occurrence of the separator if it is provided. Once the limit entries have been placed in the array, the program stops.

Example

Here, the split() function splits the string str wherever the whitespace (” “) appears and returns an array of strings. In this case, we are using the limit argument and providing the value of the limit argument as 3.

<!DOCTYPE html>
<html>
<head>
<script>
var str = 'Welcome to the i2Tutorials'
var arr = str.split(" ", 3);
document.write(arr);
</script>
</head>
<body>
</body>
</html>

Leave a comment