【问题标题】:Using wildcard in string in Javascript在 Javascript 中的字符串中使用通配符
【发布时间】:2021-02-21 20:22:55
【问题描述】:

如何在 javascript 中表示字符串中的一系列数字?

例如,

var Ages = "此成员 x 岁";

其中 x 可以是任何数字。

我希望能够在字符串数组中搜索这样的字符串。

【问题讨论】:

标签: javascript arrays wildcard


【解决方案1】:

使用正则表达式,匹配并捕获\d+(一位或多位数字)代替x

const pattern = /This member is (\d+) years old/;
const input = prompt('Input?', 'This member is 99 years old');
const match = pattern.exec(input);
if (match) {
  console.log(match[1]);
} else {
  console.log('Format not recognized');
}

【讨论】:

    【解决方案2】:

    Javascript 非常适合连接。

    var x = // the age value you are searching for;

    var ages = "The member is " + x + " years old";

    然后您可以将其包装在一个循环中。

    【讨论】:

    • 这可能不是像其他人所说的那样做你想做的最有效的方法,最好使用正则表达式。
    • 是的,使用正则表达式是正确的方法
    猜你喜欢
    • 2020-06-23
    • 2014-12-02
    • 2015-02-28
    • 1970-01-01
    • 2020-10-21
    • 2020-11-21
    • 2017-05-27
    • 1970-01-01
    相关资源
    最近更新 更多