0
Lorem ipsum dolor sit amet consectetur adipisicing elit.

Is it possible to use .replace to change everything beyond amet in the sentence above?

UserIsCorrupt
  • 4,837
  • 15
  • 38
  • 41

1 Answers1

9

It is.

str.replace(/(amet).+$/, '$1FOO')

If "amet" actually contains weird characters, you have to 'regex quote' them: ., -, [ etc.

EDIT
Explaining regex is hard.

  • (amet) => Capture a literal "amet". Capture, because you want to keep that part for the replacement, because you want to replace everything after "amet".
  • .+ => Any type of characters (.), but at least one (+). If you want at least 0, you can use * instead of +.
  • $ => the end of the subject (str). In thise case, it's unnecessary, because regex is greedy and won't stop until you tell it to (and since .+ will never stop matching, the end is the end)
  • $1 => This is a placeholder for 'the first match'. In this case, it's awlways "amet", because we matched a literal "amet". If the regex is variable, this $1 will be unknown (which is what it exists for).
  • FOO => Another literal (the replacement). Your question includes "... change everything after ..." which - in my eyes - means "replace by "FOO"".

Clear enough? If not, I'd be happy to try to explain better. Always a great resource (for young and old, wise and not-so-wise and pro's and beginners): http://www.regular-expressions.info/

To conclude: regex is AWESOME.

Rudie
  • 52,220
  • 42
  • 131
  • 173
  • 1
    Could you explain your regex? From what I can tell it matches, and remembers the match of, `amet`, but what does the rest mean? Particularly the `'$1F00'`? – David Thomas Feb 15 '12 at 21:33
  • This is exactly what I needed. Can I include `amet` in the replacement without specifying what comes before it? – UserIsCorrupt Feb 15 '12 at 21:48