开发者

How to append to an anchor's href attribute with JavaScript but not affect query string?

I have some links (they are in an array, not a elements)...

  • http://example.com
  • http://example.com?bob=true
  • http://example.com?sandy=true&bob=false

I want to append something after the .com but before the start of the query string.

Example

  • http://example.com/search/results
  • http://example.com/search/results?bob=true
  • http://example.com/search/results?sandy=true&bob=false

What is the best way?

Update

开发者_如何学编程I answered my own question, however if my solution can be improved (or you can see some problem with it) please do post your own answer.


I came up with this...

var append = '/search/results';

anchor.href = anchor.href.replace(/(\?|$)/, append + '$1'); 

I thought I could omit the parenthesis and just back reference with $0, but it didn't work for me :(


var a = document.createElement('a');
a.href = 'http://example.com/search/results?sandy=true&bob=false';
var append = '/foo/path';
alert(a.pathname + append + a.search);

http://jsfiddle.net/karim79/sYxYg/


Simplest pure regex solution I came up with

function urlappend(url, append) {
  return url.replace(/(?=\?)|$/, append);
}


urlappend('http://example.com?bob=true', '/search/results');
//returns "http://example.com/search/results?bob=true"

urlappend('http://example.com', '/search/results')
//returns "http://example.com/search/results"

For the regex curious, (?=\?) matches the the position between the first ? and the character before it.

As to whether this is the "proper" way, that is subjective. I'd say if the links you are dealing with are just strings and not nodes, this way is better. If they are already links, use karim79's method.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜