Javascript 替换字符串中的数字
好的,我有下面的字符串Javascript 替换字符串中的数字,javascript,regex,Javascript,Regex,好的,我有下面的字符串 var str = 'some text {Foo} some more text {9}'; 现在我知道如何替换特定的字符/单词,例如 var newStr = str.replace(/{Foo}/g, 'bar'); 但是,当数字可以是任何数字时,我如何替换{9}?可以将元序列用于数字\d var str='some text{Foo}some more text{9}', newStr=str.replace(/{\d+}/g,'bar'); console
var str = 'some text {Foo} some more text {9}';
现在我知道如何替换特定的字符/单词,例如
var newStr = str.replace(/{Foo}/g, 'bar');
但是,当数字可以是任何数字时,我如何替换{9}?可以将元序列用于数字
\d
var str='some text{Foo}some more text{9}',
newStr=str.replace(/{\d+}/g,'bar');
console.log(newStr)代码>您可以将元序列用于数字\d
var str='some text{Foo}some more text{9}',
newStr=str.replace(/{\d+}/g,'bar');
console.log(newStr)
您应该使用\{/d+}/g
正则表达式来匹配任何数字:
\d
元字符与数字匹配
+
量词表示1个或多个匹配类型
/g
修饰符表示执行全局匹配
var str='some text{Foo}some more text{9}';
var newstr=str.replace(/{\d+}/g,'number');
console.log(newstr);
str='一些文本{Foo}一些更多的文本{99199}和{435}';
newstr=str.replace(/\d+/g,'number');
console.log(newstr)
您应该使用\{/d+}/g
正则表达式来匹配任何数字:
\d
元字符与数字匹配
+
量词表示1个或多个匹配类型
/g
修饰符表示执行全局匹配
var str='some text{Foo}some more text{9}';
var newstr=str.replace(/{\d+}/g,'number');
console.log(newstr);
str='一些文本{Foo}一些更多的文本{99199}和{435}';
newstr=str.replace(/\d+/g,'number');
console.log(newstr)代码>您没有指定什么是“数字”,所以我设计了一个解决方案,它不仅适用于正整数,也适用于有符号整数和浮点数,并处理嵌套括号
/{\d+}/g
匹配花括号内的一个或多个数字
var str='some text{Foo}some more text{9}';
var m=str.match(/{\d+}/g);
控制台日志(m);//m=[“{9}”]
您没有指定什么是“数字”,所以我设计了一个解决方案,它不仅适用于正整数,还适用于有符号整数和浮点数,并处理嵌套括号
/{\d+}/g
匹配花括号内的一个或多个数字
var str='some text{Foo}some more text{9}';
var m=str.match(/{\d+}/g);
控制台日志(m);//m=[{9}]
newstr=str.replace(/{\d+}/g,'something')
@anubhava谢谢:)newstr=str.replace(/{\d+}/g,“某物”)代码>@anubhava谢谢:)谢谢!这正是我想要的:)谢谢!这正是我想要的:)