Search code examples
javascriptjqueryhref

Get rid of characters in url href


I have a link like this:

http://nl.wikipedia.org/wiki/Alexandra_Stan&sa=U&ei=UULHUIIdzPnhBOKMgPgJ&ved=0CCIQFjAA&usg=AFQjCNGyCikDkoZMnnuqGo6vjMQ6b5lZkw

I would like to get rid of everything starting at '&' So this will give me a clean url:

http://nl.wikipedia.org/wiki/Alexandra_Stan

I know how to replace href like this:

$('a').each(function() {
      $(this).attr("href", function(index, old) {
            return old.replace("something", "something else");
      });
});

But I can't figure out how to get rid of everything starting at a certain character.


Solution

  • You can use substr() and indexOf() to get a specific portion of the URL, from the beginning of the URL string up until the point the first ampersand is encountered.

      var href = $(this).attr('href'); 
      var url = href.substr(0, href.indexOf('&'));