0

I've got a string which contains q="AWORD" and I want to replace q="AWORD" with q="THEWORD". However, I don't know what AWORD is.. is it possible to combine a string and a regex to allow me to replace the parameter without knowing it's value? This is what I've got thus far...

globalparam.replace('q="/+./"', 'q="AWORD"');

2 Answers 2

5

What you have is just a string, not a regular expression. I think this is what you want:

globalparam.replace(/q=".+?"/, 'q="THEWORD"');

I don't know how you got the idea why you have to "combine" a string and a regular expression, but a regex does not need to exist of wildcards only. A regex is like a pattern that can contain wildcards but otherwise will try to match the exact characters given.

The expression shown above works as follows:

  • q=": Match the characters q, = and ".
  • .+?": Match any character (.) up to (and including) the next ". There must be at least one character (+) and the match is non-greedy (?), meaning it tries to match as few characters as possible. Otherwise, if you used .+", it would match all characters up to the last quotation mark in the string.

Learn more about regular expressions.

Sign up to request clarification or add additional context in comments.

Comments

2

Felix's answer will give you the solution, but if you actually want to construct a regular expression using a string you can do it this way:

var fullstring = 'q="AWORD"';
var sampleStrToFind = 'AWORD';

    var mat = 'q="'+sampleStrToFind+'"';
    var re = new RegExp(mat);
    var newstr =  fullstring.replace(re,'q="THEWORD"');

alert(newstr);

mat = the regex you are building, combining strings or whatever is needed.

re = RegExp constructor, if you wanted to do global, case sensitivity, etc do it here.

The last line is string.replace(RegExp,replacement);

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.