m3hdi
m3hdi

Reputation: 383

replace similar string in a text using javascript regex

we have a text like:

this is a test :rep more text more more :rep2 another text text qweqweqwe.

or

this is a test :rep:rep2 more text more more :rep2:rep another text text qweqweqwe. (without space)

we should replace :rep with TEXT1 and :rep2 with TEXT2.

problem: when try to replace using something like:

rgobj = new RegExp(":rep","gi");
txt = txt.replace(rgobj,"TEXT1");

rgobj = new RegExp(":rep2","gi");
txt = txt.replace(rgobj,"TEXT2");

we get TEXT1 in both of them because :rep2 is similar with :rep and :rep proccess sooner.

Upvotes: 1

Views: 139

Answers (2)

apsillers
apsillers

Reputation: 115940

If you require that :rep always end with a word boundary, make it explicit in the regex:

new RegExp(":rep\\b","gi");

(If you don't require a word boundary, you can't distinguish what is meant by "hello I got :rep24 eggs" -- is that :rep, :rep2, or :rep24?)

EDIT:

Based on the new information that the match strings are provided by the user, the best solution is to sort the match strings by length and perform the replacements in that order. That way the longest strings get replaced first, eliminating the risk that the beginning of a long string will be partially replaced by a shorter substring match included in that long string. Thus, :replongeststr is replaced before :replong which is replaced before :rep .

Upvotes: 2

Andrew Jackman
Andrew Jackman

Reputation: 13966

If your data is always consistent, replace :rep2 before :rep.

Otherwise, you could search for :rep\s, searching for the space after the keyword. Just make sure you replace the space as well.

Upvotes: 2

Related Questions