Use Regex to insert jQuery querystring before a url anchor On my page I have some content links that start with '/example/'.  I'm using jquery to add a querystring to these links, which is the parent of the currently viewed node.  So, the code looks like this:

//add parent querystring to subpages
$('a[href^="/example/"]').each(function(index, element) {
  var parentAttr = $(this).attr('href') + '?parent=' + Drupal.settings.nodeinfo.nid;
  $(this).attr('href', parentAttr);
});


This works great with one big exception.  Some of the links look like this (note the anchor at the end):

http://mysite.com/example/subpage#anchor-name


So, with my jquery, the resulting link looks like this:

http://mysite.com/example/subpage#anchor-name?parent=123


When the url is structured this way, the anchor part doesn't actually work (it doesn't jump the user to that section of the page).  The querystring actually needs to inject itself between the full url and the anchor.  This format is what's needed:

http://mysite.com/example/subpage?parent=123#anchor-name


How can I modify my code to inject the querystring before the anchor in the url if there is one?  I'm assuming it has to be regexed somehow?
Rather than writing your own solution you could just a solution that's already tried and tested, like the parse_url() function on phpjs.

It works exactly the same way as PHP's parse_url() so you can use it to extract all elements of the url, alter what you need, then build it up again.

For example calling the function like this:

var components = parse_url('http://username:password@hostname/path?arg=value#anchor');


Will yield the following result:

{
  scheme: 'http', 
  host: 'hostname', 
  user: 'username', 
  pass: 'password', 
  path: '/path', 
  query: 'arg=value', 
  fragment: 'anchor'
}


From there it'll be easy to manipulate the values you're interested in and build up a new URL, without having to resort to a another regex.

Basic example:

$('a[href^="/example/"]').each(function(index, element) {
  var components = parse_url($(this).attr('href'));

  var newUrl = components.scheme + '://' + components.hostname + '/' + components.path + '?parent=' + Drupal.settings.nodeinfo.nid + '#' + components.anchor;

  $(this).attr('href', newUrl);
});