javascript replace last occurrence of string

2020-03-01 09:08发布

问题:

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.

回答1:

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


回答2:

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.



回答3:

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');


标签: regex replace