![](/img/trans.png)
[英]How to replace last occurrence of characters in a string using javascript
[英]javascript replace last occurrence of string
我已經閱讀了StackOverflow中的許多問答,但我仍然很難獲得RegEX。 我有字符串12_13_12
。
如何用aa
代替最后一次出現的12。
最終結果應為12_13_aa
。
我真的很想對您的操作方式做出很好的解釋。
您可以使用以下替換:
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
換句話說,該模式表示:
newString = oldString.substring(0,oldString.lastIndexOf("_")) + 'aa';
使用此String.replace
並確保最后輸入$
:
repl = "12_13_12".replace(/12(?!.*?12)/, 'aa');
編輯:在正則表達式中使用變量:
var re = new RegExp(ToBeReplaced);
repl = str.replace(re, 'aa');
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.