Pet*_* O. 7 javascript replace
我想替换字符串中的字符,例如
草稿[ 2 ]
至:
草稿[ 3 ]
此正则表达式仅返回草案3:
str.replace(/\[(.+?)\]/g, 3)
Run Code Online (Sandbox Code Playgroud)
提前感谢您的帮助
ani*_*ane 13
你需要更多的东西吗?
var num=2 // parse this from drafts [2]
num++;
var newstr=str.replace(/\[(.+?)\]/g, "["+num+"]")
Run Code Online (Sandbox Code Playgroud)
或者括号可以改变为每个输入的<> {}?
您还可以提供函数而不是replace-string.
var str = "Drafts [2]";
function replacer(match, p1, p2, p3, offset, string) {
return p1 + (1+parseInt(p2)) + p3;
}
var newstr=str.replace(/([\[(])(.+?)([\])])/g, replacer);
alert(newstr); // alerts "Drafts [3]"
Run Code Online (Sandbox Code Playgroud)
使用零宽度断言而不是实际匹配括号.
编辑:Javascript没有lookbehind.:C
作为一般解决方案,您可以捕获周围的内容并使用反向引用将其放回替换字符串中.
str.replace(/(\[).+?(\])/g, "$13$2")
Run Code Online (Sandbox Code Playgroud)
或者,您可以在替换中包含硬编码括号.
小智 5
您可以像这样将括号添加到替换文本中:
str.replace(/\[(.+?)\]/g, "["+3+"]")
Run Code Online (Sandbox Code Playgroud)
编辑:如果您需要对括号中的数字执行任何操作,则可以使用函数而不是替换文本:
str.replace(/\[(.+?)\]/g, function(string, first){
// string is the full result of the regex "[2]"
//first is the number 2 from "draft [2]"
return "["+(first++)+"]";
})
Run Code Online (Sandbox Code Playgroud)