How to add href binding attribute with JavaScript but not affect the query string?

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

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

I want to add something after .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 question, however, if my solution can be improved (or you can see some problems with it), please write your own answer.

+3
source share
3 answers

I came up with this ...

var append = '/search/results';

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

I thought I could omit the brackets and only link back using $0, but this did not work for me :(

+4
source
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/

+2
source

.

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"

(?=\?) ? .

Regarding whether this is the โ€œrightโ€ way, it is subjective. I would say if the links you are dealing with are just strings, not nodes, thatโ€™s better. If they are already connected, use the karim79 method.

+1
source

Source: https://habr.com/ru/post/1778234/


All Articles