Hai Tien
Hai Tien

Reputation: 3117

Replace space with "-"?

Please check for me this script below, I don't know why it does not run. Check now :

<script>
 $("#categories li a").each(function() {

   var hreflink = (/[^/]*$/.exec(decodeURIComponent(this.href)));
   //var realhref = hreflink.replace(/\s/g, '_');
        $(this).attr("href", "#" + hreflink);
  });

</script>

Explain: I want replace all links with "category" (catch from links) Example:

I have link like :

<a href="http://www.stackoverflow.com/new%20link">New Link</a>

After replace I have only:

<a href="#new-link">New Link</a>

I decode url and then replace but replace may has problems.

Thanks for all help.

Upvotes: 1

Views: 124

Answers (3)

Arun P Johny
Arun P Johny

Reputation: 388326

The exec function returns an array, you need to get the first item in the array

$("#categories li a").attr('href', function (_, href) {
    var hreflink = (/[^/]*$/.exec(decodeURIComponent(href)))[0];
    return hreflink.replace(/\s/g, '_');
});

Demo: Fiddle

Upvotes: 1

codingrose
codingrose

Reputation: 15699

Try:

$("a").each(function(){
    var href = $(this).attr("href");
    href = href.replace(/%20/g,"-");
    href = href.replace(/ /g,"-");
    href = href.split("/").pop();
    $(this).attr("href","#"+href);
});

Fiddle here.

Upvotes: 1

Rahul Tripathi
Rahul Tripathi

Reputation: 172418

You may try this:

.replace(/\s/g,"-");

JSFIDDLE

Upvotes: 1

Related Questions