0

Ok, I am not sure what is wrong with me, but I am trying to find and replace a portion of multiple URLs.

Basically, I have some URLs that are being dynamically added to my site. All have a class of 'newsLink' some of the links are pulling up google.docs viewer and I need to remove that.

Here is my code thus far:

$('a.newsLink').each(function(){
var lnk = $('a.newsLink').attr();
var re = new RegExp("http://docs.google.com/viewer?url=","g");
lnk.replace(re, "");
});

the links look like:

<a href='http://docs.google.com/viewer?url=myHomePage.pdf' class='newsLink' target='_blank'>

I would like to remove the first part so that the link looks like:

<a href='http://myHomePage.pdf' class='newsLink' target='_blank'>

Anyway, no luck this far...can anyone please help.

2 Answers 2

2

First, you are getting all links again inside of the loop. Then, you try to get an attribute, but didn't say which one. Finally, you try to use replace without assigning the return value to anything.

This is what your code should be:

$('a.newsLink').each(function(){
    var lnk = this.href;
    this.href = lnk.replace("http://docs.google.com/viewer?url=", "");
});

Note: I'm assuming you want the links to become e.g. myHomePage.pdf, without the protocol.

Sign up to request clarification or add additional context in comments.

3 Comments

Okay, I dumped the regex entirely, after all it's not necessary. Now it works.
Cool. Even better than mine now.
Swiftly solution bro, since the URL is always a literal string (no alternation or iteration in the part which needs to be replaced), regex is unneeded. +1
1

The regular expression you want is.

http:\/\/docs\.google\.com\/viewer\?url=(.+)

First off, this escapes all regular expression characters. In this case \, ., and ?. We are capturing the document using a group that matches every character ((.+)).

So our code looks like this so far.

$('a.newsLink').each(function(){
    var lnk = this.href;
    var re = /http:\/\/docs\.google\.com\/viewer\?url=(.+)/g
    this.href = lnk.replace(re, "");
});

Now we get the groups like so.

var match = re.exec(lnk);

This returns an array of the matches. Our document is now stored in match[1]. So our final code comes out to.

$('a.newsLink').each(function(){
    var lnk = this.href;
    var re = /http:\/\/docs\.google\.com\/viewer\?url=(.+)/g
    this.href = (re.exec(lnk))[1];
});

Comments

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.