IMG-LOGO

How to split string in Javascript?

andy - 22 Dec, 2013 2919 Views 0 Comment

This tutorial will show how you can split a string or words by using the built in split function in Javascript

To split a string in Javascript is pretty simple, you will just need to using the following syntax. There will be two parameters available:

string.split(separator_symbol, no_of_splits)

Note: the last parameter which is no_of_splits is optional

var sampleString = "one;two;three;four;five";
var arrString = sampleString.split(";");

for(i = 0; i < arrString.length; i++){
    alert(arrString[i]);
}

/* The above for loop function will return the following 5 alert message box: */
one
two
three
four
five

Here is another example that you want to get the first two splits only.

var sampleString = "100,200,300,400,500";
var arrString = sampleString.split(",", 2);

for(i = 0; i < arrString.length; i++){
    alert(arrString[i]);
}

/* The above for loop function will return the following 2 alert message box: */
100
200

Comments

There are no comments available.

Write Comment
0 characters entered. Maximum characters allowed are 1000 characters.

Related Articles