简体   繁体   中英

javascript replace last occurrence of string

I've read many Q&As in StackOverflow and I'm still having a hard time getting RegEX. I have string 12_13_12 .

How can I replace last occurrence of 12 with, aa .

Final result should be 12_13_aa .

I would really like for good explanation about how you did it.

You can use this replace:

var str = '12-44-12-1564';
str = str.replace(/12(?![\s\S]*12)/, 'aa');
console.log(str);

explanations:

(?!            # open a negative lookahead (means not followed by)
   [\s\S]*     # all characters including newlines (space+not space)
               # zero or more times
   12
)              # close the lookahead

In other words the pattern means: 12 not followed by another 12 until the end of the string.

newString = oldString.substring(0,oldString.lastIndexOf("_")) + 'aa';

Use this String.replace and make sure you have end of input $ in the end:

repl = "12_13_12".replace(/12(?!.*?12)/, 'aa');

EDIT: To use a variable in Regex:

var re = new RegExp(ToBeReplaced);
repl = str.replace(re, 'aa');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM