2

I'm trying to fix all the links on a blog but instead of editing each post manually I decided to write a simple script to do it automatically. How can I use jquery to replace an unknown number in a link? In this case I'm trying to remove it to fix the formatting.

Here's the HTML

<a href="http://www.example.com/2016/10/%20http://www.newlink.com">LINK</a>

Script

$("a").each( function() {
   this.href = this.href.replace("http://www.example.com/XXXX/XX/%20","");
});

Final output should be

<a href="http://www.newlink.com/anypost.html">LINK</a>
3
  • You want to replace only numbers in a link ? or anything other than "newlink.com" ? Commented Oct 24, 2016 at 15:46
  • Sorry I wasn't specific. Basically I want to remove example.com/2016/10/%20 from the url. The new link is not fixed. Commented Oct 24, 2016 at 15:49
  • Why not just do this.href = this.href.substring(this.href.indexOf('http://www.newlink.com'));. Then you don't need to worry about numbers at all. Commented Oct 24, 2016 at 15:50

1 Answer 1

4

You can do it using RegExp. Basically it's - replace everything before the first %20 including the %20.

$("a").each( function() {
   this.href = this.href.replace(/^.+%20?/, '');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a href="http://www.example.com/2016/10/%20http://www.newlink.com">LINK</a>

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

1 Comment

This is exactly what I need. Thank you!

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.