7

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 this question:

How to replace last occurrence of characters in a string using javascript

But it doesn't fit my needs. As a background, I will say that I am trying to replace a CSS rule, but for the current example lets look at this text:

abcd:bka:

bbb:aad:

accx:aaa:

bbb:a0d:

cczc:aaa:

lets say I only want to replace the value of bbb. My current rule will be

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

but it will only replace the first match, while I want it to replace the last one. My current pattern is actually more complex than this one, but I think the pseudo problem will suffice.

1 Answer 1

8

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I like this answer: stackoverflow.com/questions/843049/… Preface with (.*) to eat up as much as possible before matching.
@PeterEhrlich: You'd have to use [\s\S]* instead (the dot doesn't match newlines), and I generally prefer being explicit to using unspecific regexes like .*, but yes, that would work, too. Whether its performance will be better or worse than mine depends on the actual text this is being used on. I'd suspect that it's going to be worse on large texts because of all the backtracking that .* causes.

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.