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?

2
  • 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. Commented Apr 6, 2011 at 11:38
  • Apologies, didn't notice it - have updated with context in which the js is being (or would like to be) used. Commented Apr 6, 2011 at 11:43

1 Answer 1

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 + '=)([^&]*)')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.