3

I've got a pattern to find matches in a querystring:

'url.com/foo/bar?this=that&thing=another'.replace(/(thing=)([^&]*)/, '$1test')

What I'd like to be able to do is use variable values as the param to match like:

'url.com/foo/bar?this=that&thing=another'.replace('/(' + key + '=)([^&]*)/', '$1test')

[edit] Here's the context in how the code is being used:

GetSrcParam: function(key, value) {
            var newSrc = $(this._image).attr('src'),
                pattern = '(' + key + '=)([^&]*)';

            if (newSrc.match(pattern) == null)
                newSrc += '&' + key + '=' + value;
            else
                newSrc = newSrc.replace(newSrc, '$1' + value);

            return newSrc;
        }

But it's not working as intended - can anyone help?

  • Welcome to SO. Please use code formattng (you only have to push a button). - Also please provide some JS code, not just the patterns themselves. The problem probably ies in how you prepare your pattern. – vbence Apr 06 '11 at 11:38
  • Apologies, didn't notice it - have updated with context in which the js is being (or would like to be) used. – Phil Cooper Apr 06 '11 at 11:43

1 Answers1

3

If you choose to construct a regex from a string, you need to drop the delimiters (but then you need to double any backslashes, if your regex were to contain any). Try

myregex = new RegExp('(' + key + '=)([^&]*)')
'url.com/foo/bar?this=that&thing=another'.replace(myregex, '$1test')

Are you aware that this would also match thing=another in url.com/foo/bar?something=another? To avoid this, add a word boundary anchor:

myregex = new RegExp('(\\b' + key + '=)([^&]*)')
Tim Pietzcker
  • 328,213
  • 58
  • 503
  • 561