Signup/Sign In

How to explode or split a string in JavaScript

Answer: Using split() function

The split() function is used to split the string into the array of strings by separating it into the substring using the specified separator within the split() function.

If we pass the empty string as a separator, it will split the string between each character.

We can not change the existing string using the split() function.

Syntax

split(separator, limit)

The separator parameter specifies where each split will occur within the input string. The separator can be a string or a regular expression.

The limit function specifies the number of the substring to be included within the array. The value of the limit parameter can be 0 or any positive integer.

Example: Splitting a string into characters

In the given example, we have split the string Studytonight into the array of characters using the JavaScript split() function.

<!DOCTYPE html>
<html lang="en">
<head>
	<title>Explode or split a string in JavaScript</title>
</head>
<body>
    <script>
    	let str = 'Studytonigt';
    	let newStr = str.split("");
    	document.write(newStr);
    </script>
</body>
</html>

Output

split()

Example: Splitting a string into words

In the given example, we have split the string into words instead of characters using the split() function. When we pass an empty string (" ") within the split() function then it will split the string into words instead of characters.

<!DOCTYPE html>
<html lang="en">
<head>
	<title>Explode or split a string in JavaScript</title>
</head>
<body>
    <script>
    	let str = 'Welcome to Studytonigt';
    	let newStr = str.split(" ");
    	document.write(newStr);
    </script>
</body>
</html>

Output

split()_2

Example: Specifying the limit

In the given example, we have split the string by specifying the limit. Firstly, we have split the string into characters and specify the limit for it and then we have split the same string into words and specify the limit for them as well.

<!DOCTYPE html>
<html lang="en">
<head>
	<title>Explode or split a string in JavaScript</title>
</head>
<body>
    <script>
    	let str = 'Welcome to Studytonigt';
    	let newStr = str.split("", 7);
    	document.write(newStr + "<br>");

    	let myStr = str.split(" ", 2);
    	document.write(myStr);
    </script>
</body>
</html>

Output

split()_3

Conclusion

In this lesson, we have discussed how to split the string using JavaScript. So JavaScript offers a built-in function to split the string named split(). With the help of this function, we can split the string into characters and words as well. It takes two parameters, the first one is a separator, and the second parameter is a limit. The separator parameter specifies where each split should occur, while the limit parameter specifies the limit on the number of substrings included within the array.



About the author: