Reputation: 490303
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.
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?
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
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
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
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