1

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?

1

3 Answers 3

7

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'
Sign up to request clarification or add additional context in comments.

Comments

2
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

0

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.

1 Comment

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.)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.