alex
alex

Reputation: 490303

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)...

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

Example

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.

Upvotes: 3

Views: 1627

Answers (3)

MooGoo
MooGoo

Reputation: 48240

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.

Upvotes: 1

karim79
karim79

Reputation: 342655

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/

Upvotes: 2

alex
alex

Reputation: 490303

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 :(

Upvotes: 4

Related Questions