const str = 'This is _XXX_0_ an example',
target = ['just', 'nothing', 'bla'];
现在我需要从该字符串中获取数字,因为 _XXX_
数字 _
是固定格式,以获取应替换虚拟字符串的元素。
我尝试过这个:
str.replace(/_XXX_(/d+)_/, target[$i]);
数值可能介于 0 到 100 之间。我做错了什么?
此示例的结果是:
This is just an example
最佳答案
I tried this:
str.replace(/_XXX_(/d+)_/, target[$i]);
有两个问题:
您需要的是
\d
,而不是/d
。上面是一个语法错误。target[$i]
将被评估,然后传递给replace
。除非在某处定义了$i
,否则您可能会收到ReferenceError
。
您可能想将其设为一个函数:
const result = str.replace(/_XXX_(\d+)_/, function(m, c0) {
return target[c0];
});
该函数接收整体匹配作为第一个参数,然后接收任何捕获组作为后续参数。
示例:
const str = 'This is _XXX_0_ an example',
target = ['just', 'nothing', 'bla'];
const result = str.replace(/_XXX_(\d+)_/, function(m, c0) {
return target[c0];
});
console.log(result);
关于javascript - 从虚拟字符串中获取数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39914877/