1

I have a string that looks something like this:

{theField} > 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?

1
  • 1
    DAY+ matches DAYYYYYYYY. Don't know if it's what you want. Commented Apr 2, 2010 at 7:28

1 Answer 1

1

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 + from DAY+ 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
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.