javascript替换最后一次出现的字符串

时间:2013-07-23 11:14:32

标签: regex replace

我在StackOverflow中读过很多Q& As,但我仍然很难获得RegEX。 我有字符串12_13_12

如何将最后一次出现的12替换为aa

最终结果应为12_13_aa

我真的很想解释你是如何做到的。

3 个答案:

答案 0 :(得分:25)

您可以使用此替换:

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

说明:

(?!            # 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

换句话说,模式意味着: 12不会跟随另一个12直到字符串结束。

答案 1 :(得分:14)

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

答案 2 :(得分:3)

使用此String.replace并确保最后输入$

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

编辑:在Regex中使用变量:

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