hi guys, 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?
+7
A:
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'
Jonathan Sampson
2009-08-21 11:46:19
+2
A:
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.
chills42
2009-08-21 11:49:38
A:
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.
mmmmmmmmm carrot
Zoidberg
2009-08-21 11:54:32
WTF is carrot character?...
Psionides
2009-08-21 11:55:52
^
Jeremy Cron
2009-08-21 12:00:04
Actually it's a caret... http://en.wikipedia.org/wiki/Caret
chills42
2009-08-21 12:00:41
You have to deal with HTML escaping anyway; avoiding the ampersand won't change that. The OP's example string looks like a URL query, in which case the ampersand is unavoidable. (Some frameworks do allow one to use a semicolon instead, as recommended by the HTML4 specification, but sadly the most popular ones today don't.)
bobince
2009-08-21 14:32:03