Phil Cooper
Phil Cooper

Reputation: 33

Javascript regexp: Using variables in backreference pattern?

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?

Upvotes: 3

Views: 770

Answers (1)

Tim Pietzcker
Tim Pietzcker

Reputation: 336498

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 + '=)([^&]*)')

Upvotes: 3

Related Questions