Saturday, April 4, 2009

Split String In Javascript.

Hi we will see How to split string in javasript..

Like C# Function You can Also Split string from some characters.

for example to split String

(1)var str1="123456789";

we can use regular expression

(1)var tmpArr= str1.match(/[1-9]/g)

In Example (1) str1.match will return Array of matching elements .

array tmpArr will contain array of elements (1,2,3,4,5,6,7,8,9)

(2)var str2="1,2,3,a,b,c";

We can Use Split function of string object.

(2) var tmpArr= str2.split(',');

In Example (2) array tmpArray Contains elements separated from character (,)

You can also use Regular Expression as argument of Split Function.

this will help you in splition string from multiple characters

(3)var str3="1,2,3-4,5,6";

to split this from( , ) as well ( - ) you can use Below Javascript.

(3) var tmpArr=str3.split(/[,-]/);

here tmpArray Contains 1,2,3,4,5,6 as Elements...