[英]javascript regular expression to match {0}
What will be the regular expression to match {0} in a piece of text? 与一段文本中的{0}匹配的正则表达式是什么? so that if I have 这样,如果我有
var temp = 'this is my {0} attempt';
I could use that regular expression in javascript to get the {0} out of 'temp', and replace with whatever text I want. 我可以在javascript中使用该正则表达式使{0}脱离'temp',并替换为所需的任何文本。
Thanks 谢谢
temp = temp.replace("{0}", "your text")
Regex is definitely not needed for this! 绝对不需要正则表达式!
Ofcourse, you can do the following as well: 当然,您也可以执行以下操作:
temp = temp.replace(/{\d+}/, "your text")
Response to @Giacomo: 对@Giacomo的回复:
temp = temp.replace("{\d+}", "your text")
will not replace anything. 不会替代任何东西。 {\\d+}
is treated as a string and not regex {\\d+}
被视为字符串,而不是正则表达式
If you want to replace with something based on what the number is inside the curly braces, you could do this: 如果要根据花括号中的数字替换为某些内容,可以执行以下操作:
var replaced = original.replace(/\{(\d+)\}/g, function(_, digits) {
return getReplacement(Number(digits));
});
You'd then write the function "getReplacement()" to return something based on the index from the original string. 然后,您将编写函数“ getReplacement()”以基于原始字符串的索引返回某些内容。
/\{\d\}/
\n
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.