Lorem ipsum dolor sit amet consectetur adipisicing elit.
Is it possible to use .replace
to change everything beyond amet
in the sentence above?
Lorem ipsum dolor sit amet consectetur adipisicing elit.
Is it possible to use .replace
to change everything beyond amet
in the sentence above?
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.