从一个虚拟字符串中得到一个数字

Get a number out of a dummy string

本文关键字:一个 数字 字符串 虚拟      更新时间:2023-09-26
const   str = 'This is _XXX_0_ an example',
        target = ['just', 'nothing', 'bla'];

现在我需要从该字符串中获取数字,因为_XXX_ number _是固定格式,以获得应该替换虚拟字符串的元素。

我试过了:

str.replace(/_XXX_(/d+)_/, target[$i]);

数值可以在0到100之间。我做错了什么?

这个例子的结果是:

This is just an example

我试过了:

str.replace(/_XXX_(/d+)_/, target[$i]);

这里有两个问题:

  1. 您需要'd,而不是/d。以上是一个语法错误。

  2. target[$i]将被求值,然后传递给replace。大概你会得到一个ReferenceError,除非$i在某处被定义。

你可能想让它成为一个函数:

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);