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?
3 Answers
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.
Comments
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.