JamesG JamesG - 1 month ago 12
HTML Question

jQuery Regex not picking up

ok, so I have checked about 4 different SO Questions and none have given me the answer. :(

A website I am working on had a few hundred pages but unfortunately the structure of the tags in the url has changed. and guess what, the pages are hard coded with text and links (FML) anyway a quick fix for now would be to get query to change all these links.

I decided to try using this:

$(document).ready(function() {
$('a').each(function() {

var str2 = "tag=";
var link = $(this).attr('href');
if(link.indexOf(str2) != -1){

var link = link.replace("/tag=.*/","tag/$1");
$(this).attr('href', link);
}
});

})


What I need is to get the value of the 'href' scan for the 'tag=ecommerce' or 'tag=b2b' etc and change the structure to 'tag/eccommerce' or 'tag/b2b'

However it just is not working.

What am I missing?

Answer

You need to use the regex syntax /YourRegex/ instead of "/YourRegex/". And use a capturing group like so:

$(document).ready(function() {
$('a').each(function() {

    var str2 = "tag=";
    var link = $(this).attr('href');
    if(link.indexOf(str2) != -1){

        var link = link.replace(/tag=(.*)/,"tag/$1");
        $(this).attr('href', link);
    }
});

});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<a href="www.foo.com/tag=MyTag">MyLink</a>