Skip to content Skip to sidebar Skip to footer

Using Regex To Replace Only The Last Occurrence Of A Pattern With JS

I have a case where I'm trying to replace a certain pattern with another. My problem is that I need to only replace the last occurrence of that pattern, not all of them. I've found

Solution 1:

Try

text.replace(/(\s*bbb:)(?![\s\S]*bbb:)[^:]+/,"$1aaa")

The negative lookahead assertion makes sure that there is no further bbb: ahead in the text. The parentheses around [^:]+ are unnecessary.

Explanation:

(?!       # Assert that it is impossible to match the following after the current position:
 [\s\S]*  # any number of characters including newlines
 bbb:     # the literal text bbb:
)         # End of lookahead assertion

The [\s\S] workaround is necessary because JavaScript doesn't have an option to allow the dot to match newlines.


Post a Comment for "Using Regex To Replace Only The Last Occurrence Of A Pattern With JS"