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

Ver*_*iel 13 regex replace

我在StackOverflow中阅读了很多问答,但我仍然很难获得RegEX.我有字符串12_13_12.

如何用,替换最后一次出现的12 aa.

最终结果应该是12_13_aa.

我真的很想解释你是怎么做到的.

Cas*_*yte 26

您可以使用此替换:

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

解释:

(?!            # 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
Run Code Online (Sandbox Code Playgroud)

换句话说,模式意味着:12在字符串结束之前不会跟随另一个12.

  • +1使用正则表达式解决方案并添加详细说明. (4认同)

Gin*_*s K 15

newString = oldString.substring(0,oldString.lastIndexOf("_")) + 'aa';
Run Code Online (Sandbox Code Playgroud)