tags:

views:

196

answers:

2

I'm trying to return a part of the url as a string and add it elsewhere.

So I do something like this:

var somestring = $("#hello").attr("href").text().replace(/part\/(\d+)/g, "part-$1");

Only I don't think this is correct. What's the correct way to do return the "part-$1" as a string?

Thanks!

Here's the example:

http://jsbin.com/agiyu/edit

If successful the output should be something like Fake Urlpart-333.

Thanks!

A: 

Try:

var somestring = $("#hello").attr("href").replace(/^.*\/part\/(\d+).*$/g, "part-$1");
$("#hello").append(somestring);
  • You don't need to call text() because attr() returns a string.
  • You forgot a closing quotation mark.
  • Since $("#hello") returns a single element, there is no need for each().
Ayman Hourieh
Thanks, I tried something like this: http://jsbin.com/itaji/editIt doesn't seem to work though.
Mark
@Mark - the code in your link still contains the first 2 issues: you are calling replace() before text(), and there is a missing quotation mark.
Ayman Hourieh
Thanks a lot.I've revised the example as per your tips:http://jsbin.com/agiyu/edit1. OK2. Got it :)3. Sorry about that. :)But it's still not working though. :(
Mark
Thanks Ayman I fixed my initial post. Though the two newer links should be better, as per your suggestions about text() coming first.
Mark
I've just noticed that you actually don't need to call text() at all, since attr() returns a string. I've updated my code.
Ayman Hourieh
Hi, Ayman, the reason why I had text() at the end was because I was just trying to return the replaced string, that is, the part-333 portion, not the entire href. Removing the .text() returns the entire href. Do you know how I can return just the replaced portion and not the entire href without using additional regex (because the actual href I'll end up using is much stranger)?Thanks a lot for your help!
Mark
OH nevermind, regex works fine!Thanks!var somestring = $("#hello").attr("href").replace(/^.+part\/(\d+).+/g, "part-$1");
Mark
I edited my answer according to your latest comment, just to find that you arrived at the same solution. :)
Ayman Hourieh
A: 

Here's a hint:

document.write(document.location.protocol);
document.write(document.location.host);
document.write(document.location.pathname);
C. Alan Zoppa
Thanks for your hint. If you're saying I use one of those to get parts of the url then that won't really work for me. The href is just an example, I'd really much rather use regex, which works fine anyway!I apologize in advance if I misinterpreted your hint.
Mark