1

I've this URL replace query:

window.history.pushState(null, null, window.location.search.replace(/\bcolor=[^&]*/, '$&,Red'));

It works like it should but how can I change the first thing and replace color by a variable do make this dynamically like this way:

var value = 'color';
window.history.pushState(null, null, window.location.search.replace(/\b  var_in_here  =[^&]*/, '$&,' + filter_value.attr('data-value') + ''));

Update

Because of the first answer from Jonas I've tried this here but it don't works:

var re = new RegExp('\b' + name + '=[^&]*');
window.history.pushState(null, null, window.location.search.replace(re, '$&,' + filter_value.attr('data-value') + ''));
Mr. Jo
  • 4,946
  • 6
  • 41
  • 100
  • This was a follow up question on https://stackoverflow.com/questions/53677336/append-value-to-url-search-param – Jonas Wilms Dec 07 '18 at 23:20
  • Yes you are right :) good job! But this is not related to the question. The question was how I can add values. This question is about replacing static regex identifiers by variables. I'm just following the rules. For each topic a new question. – Mr. Jo Dec 07 '18 at 23:24
  • 1
    yes, this is definetly a new question but others answering should be able to see "the big picture" – Jonas Wilms Dec 08 '18 at 09:39

1 Answers1

3

You could dynamically build up the regex:

 new Regex("\\b" + name + "=[^&]*")

Two \ are needed to get this working.

Mr. Jo
  • 4,946
  • 6
  • 41
  • 100
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151