Vianne Yu Zhèng Vianne Yu Zhèng - 1 month ago 7
Javascript Question

Replace Any Number in a URL using Jquery

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>

Answer

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>

Comments