Problem with Javascript RegExp-mask
I have a string that looks something like this:
{theField}开发者_Go百科 > YEAR (today, -3) || {theField} < YEAR (today, +3)
I want it to be replaced into:
{theField} > " + YEAR (today, -3) + " || {theField} < " + YEAR (today, +3) + "
I have tried this:
String.replace(/(.*)(YEAR|MONTH|WEEK|DAY+)(.*[)]+)/g, "$1 \" + $2 $3 + \"")
But that gives me:
{theField} > YEAR (today, +3) || {theField} > " + YEAR (today, +3) + "
Does anyone have any ideas?
You should be careful using greedy matching when you have .*
. Usually this doesn't do what you want - it matches as much of the string as possible. You either need to use a negative character class to stop matching when you reach a certain character (e.g. [^)]
) or else use a lazy match .*?
. Here is how you could do it using the lazy quantifier:
s = '{theField} > YEAR (today, -3) || {theField} < YEAR (today, +3)';
result = s.replace(/((YEAR|MONTH|WEEK|DAY).*?\))/g, '" + $1 + "')
Result:
{theField} > " + YEAR (today, -3) + " || {theField} < " + YEAR (today, +3) + "
Note that I've cleaned up a bit in your regular expression:
- Removed the
+
fromDAY+
as KennyTM noted - Changed
[)]+
to\)
- Changed the literal replacement string from double-quoted to single-quoted so that the quotes in the replacement text don't need to be escaped
- Removed the extra space you were putting into the result between YEAR and the following opening parenthesis
精彩评论