String question

K

Ken Smith

Possible solution:

Copy and save as testme.html

<HTML>

<SCRIPT>

//Get the full URL

theFullURL=document.location.href;

document.write("The Full URL:"+theFullURL+"<BR>");

//Index the ID part of string

id=theFullURL.indexOf("id=");

document.write("Index of URL:<B>"+id+"</B><BR>");

//Get the following string from index

//(+2 to get rid of 'id=')

idVal=theFullURL.substring(id+2);

document.write("ID:<B>"+idVal+"</B>");

</SCRIPT>



<HTML>

When you run the HTML in explorer add your other values.

(i.e

ORIGINAL:

C:\test\testme.html

RUN Like:

C:\test\testme.html?action=shownesitem&id=125

)

Worked for me!

Ken
 
G

Grant Wagner

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,776
Messages
2,569,603
Members
45,190
Latest member
ClayE7480

Latest Threads

Top