[英]Javascript: Replace all occurences of ' a ' in a string with ' b ' with a regex
[英]Javascript Regex - Replace all occurences of matching string EXCEPT any string between brackets
我需要替換在另一個實例內部具有字符串的字符串,但是如果替換在大括號內的任何字符串,則忽略該字符串。
我嘗試了以下方法:
str = "replace {replace} test replacesreplace"
str.replace(/{[^}]*}|(replace(s)?)/g, "%")
// % % test %%
str = "replace {replace} test replacesreplace"
str.replace(/{[^}]*}|(replace(s)?)/g, "$1"+"%")
// replace% % test replaces%replace%
但是我需要這樣替換: "% {replace} test %%"
任何人都可以建議如何在Javascript中執行此操作嗎?
您可以將函數與String.replace()
。 如果找到捕獲,則返回括號內的內容,否則返回%
。
var str = "replace {replace} test replacesreplace"; str = str.replace(/({[^}]*})|replaces?/g, function($0, $1) { return typeof $1 != 'undefined' ? $1 : "%"; }); document.write(str);
使用負向超前
(?!\{)replace(?!\})
(?!\\{)
:負前瞻-斷言不可能匹配{
文字 replace
:匹配字面上的replace
字符串 (?!\\})
:負超前-斷言不可能匹配}
文字 Javascript示范
var str = "replace {replace} test replacesreplace"; var replacedStr = str.replace(/(?!\\{)replace(?!\\})/g, "%"); document.write(replacedStr);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.