Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/392.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript JS正则表达式替换字符串中的数字_Javascript_Regex_String - Fatal编程技术网

Javascript JS正则表达式替换字符串中的数字

Javascript JS正则表达式替换字符串中的数字,javascript,regex,string,Javascript,Regex,String,我正在尝试使用JS.replace将整数替换为字符串,以了解一些正则表达式 例如,字符串可以是: var string = 'item_descriptions_0_additional_details'; 我想用另一个值替换0。我最初使用的是: string.replace( /\[\d\]/g, '[newvalue]'); 但它不起作用。我对Regex很陌生 提前谢谢。非常感谢。您所拥有的 \[\d\] \[-表示匹配[ \d-匹配任意数字 \]-匹配] 因为在字符串中没有任何

我正在尝试使用JS.replace将整数替换为字符串,以了解一些正则表达式

例如,字符串可以是:

 var string = 'item_descriptions_0_additional_details';
我想用另一个值替换
0
。我最初使用的是:

string.replace( /\[\d\]/g, '[newvalue]');
但它不起作用。我对Regex很陌生

提前谢谢。非常感谢。

您所拥有的

\[\d\]
  • \[
    -表示匹配
    [
  • \d
    -匹配任意数字
  • \]
    -匹配
    ]
因为在字符串中没有任何与regex模式匹配的序列,所以它不会进行任何替换


您需要使用
\d

var string='item_descriptions_0_additional_details';
让op=string.replace(/\d/g,“[new value]”);

console.log(op)
首先,因为
string.replace
返回一个新字符串,它不会改变旧字符串,所以需要将
string.replace
的结果分配给变量。其次,您有一个无效的正则表达式:

var string='item_descriptions_0_additional_details';
string=string.replace(/\d+/g,“[newvalue]”);

console.log(字符串)
尝试
\d+
捕获任何数字序列的第一次出现(长度至少为一个字符)

var string='item_descriptions_0_additional_details';
var r=string.replace(/\d+/,“[new value]”);
控制台日志(r)