1

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.

Youss
  • 4,196
  • 12
  • 55
  • 109
  • Please consider [this](http://stackoverflow.com/a/2541083/227646) answer on Stack Overflow. Never mind. Both the answers below are better suited than what I had. – kush Dec 11 '12 at 14:38
  • is that even a valid URI without a `?` for the first qs param? – jbabey Dec 11 '12 at 14:41
  • @jbabey What do you mean...It takes you to the page right? – Youss Dec 11 '12 at 14:43
  • @Youss if any server code (.NET, PHP, etc) attempts to retrieve any querystring values it will throw exceptions. The querystring portion of a URI must begin with `?`. [Reference](http://en.wikipedia.org/wiki/Query_string#Structure) – jbabey Dec 11 '12 at 14:52

3 Answers3

8

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('&')); 
Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
1

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/'
danronmoon
  • 3,814
  • 5
  • 34
  • 56
0

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

freedev
  • 25,946
  • 8
  • 108
  • 125