Youss
Youss

Reputation: 4212

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.

Upvotes: 1

Views: 289

Answers (3)

Jay Blanchard
Jay Blanchard

Reputation: 34406

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('&')); 

Upvotes: 8

danronmoon
danronmoon

Reputation: 3873

Use String.prototype.split instead. It splits a string by character into an array. The most important part is that if that character is missing (in your case, '&'), it will put the entire string in the first array index anyway.

// String.prototype.indexOf:
var href = 'http://www.noAmpersandHere.com/',
    url  = href.substr(0, href.indexOf('&'));  // ''

// String.prototype.split:    
var href = 'http://www.noAmpersandHere.com/',
    url  = href.split('&');  // ['http://www.noAmpersandHere.com/']
    url  = url[0];  // 'http://www.noAmpersandHere.com/'

Upvotes: 1

freedev
freedev

Reputation: 30037

First: consider that the parameters list starts with ? and not with &

The anchor element you are handling already have the entire url parsed and correctly divided. You need only to access to the correct anchor property:

https://developer.mozilla.org/en-US/docs/DOM/HTMLAnchorElement

Upvotes: 0

Related Questions