Arjen said:
Hello,
I have inside a string a complete url.
http://www.somedomain.com/index.php?action=shownewsitem&id=125
At the end you see "id=", the id can be "1", "23", "234", etc..
Now I want to have the Id in a new variable.
How can catch the id?
Thanks!
If it's always "id=", just use:
(new RegExp("id=(\\d+)")).test(window.location.search);
var id = RegExp.$1;
alert(id);
window.location.search might look something like:
"?param=blah&id=123&somethingelse=something" so:
(new
RegExp("id=(\\d+)")).test("?param=blah&id=123&somethingelse=something");
var id = RegExp.$1;
alert(id); // alerts "123" which is correct
The nice thing about using (new RegExp()).test(); var x =
RegExp.$1; is that you always either get the string you are looking
for, or you get an empty string. It never causes an error, it never
results in a null value. The *only* thing to be aware of is if you
were looking for something other then numbers, then you need to
make sure you don't pick up the entire query string:
(new RegExp("param=(.[^&]+)")).test(window.location.search);
Lastly, if you're looking for a lot of values on the query string,
this mechanism is better replaced with something that retrieves all
the key/value pairs as an object's properties/values. And this
mechanism doesn't support multiple same named items on the query
string (although it could be modified to).
--
| Grant Wagner <
[email protected]>
* Client-side Javascript and Netscape 4 DOM Reference available at:
*
http://devedge.netscape.com/library/manuals/2000/javascript/1.3/reference/frames.html
* Internet Explorer DOM Reference available at:
*
http://msdn.microsoft.com/workshop/author/dhtml/reference/dhtml_reference_entry.asp
* Netscape 6/7 DOM Reference available at:
*
http://www.mozilla.org/docs/dom/domref/
* Tips for upgrading JavaScript for Netscape 7 / Mozilla
*
http://www.mozilla.org/docs/web-developer/upgrade_2.html