user42348
user42348

Reputation: 4319

Splitting strings in javascript

I have variable named s in javascript.It contains value as '40&lngDesignID=1'.I want to split it with & and want to get 40 and lngDesignID=1.How can i do that in javascript?Can anybody help?

Upvotes: 1

Views: 1573

Answers (3)

austin cheney
austin cheney

Reputation:

Don't use the ampersand for any sort of string operation. If you ever have to compare variables who obtain their values from HTML and contain ampersands you will find the ampersands converted into entities, which messed up your comparison or evaluation. Use some other character that you would never otherwise use, such as a tilde or caret.

Upvotes: 0

chills42
chills42

Reputation: 14513

var yourString = '40&lngDesignID=1';

var arr = yourString.split('&');
alert(arr);

Then arr[0] will hold '40' and arr[1] will hold the value 'lngDesignID=1'.

Also, javascript split accepts regular expressions, so you could also break up the string further if needed.

var yourString = '40&lngDesignID=1';

var arr = yourString.split(/[&=]/);
alert(arr);

This version splits the input into 3 parts; 40, lngDesignID, and 1.

Upvotes: 2

Sampson
Sampson

Reputation: 268344

Use s.split("&") to return an array of elements.

var string = "40&lngDesignID=1";
var splitVals = string.split("&");

alert(splitVals[0]); // Alerts '40'
alert(splitVals[1]); // Alerts 'lngDesignID=1'

Upvotes: 7

Related Questions