JavaScript Tips & Tutorials

JavaScript: Split and Divide Text String by A Delimiter

Spliting and dividing a string into several chunks is a rather basic need for text parsing. You can do it easily in PHP by the help of explode() function or preg_split(), in JavaScript, you can achieve this task by the split() string function.

The following example illustrates the usage of javascript split() function to slice a string into various parts in an array.

var str = "How are you";
var words = str.split(" "); //split using a single blank space as the delimiter
for (i = 0; i < words.length; i++) {
	alert(words[i]); //alerts "How", "are" and "you" sequentially

Note that split is a method of string objects in JavaScript, not standalone functions. Therefore, you can even use it this way:

var words = "How are you".split(" ");

By Yang Yang

Hello, I'm Yang. I build online businesses that please people. Want to join in and post some useful articles on Shoot me a message.