【发布时间】:2021-02-21 20:22:55
【问题描述】:
如何在 javascript 中表示字符串中的一系列数字?
例如,
var Ages = "此成员 x 岁";
其中 x 可以是任何数字。
我希望能够在字符串数组中搜索这样的字符串。
【问题讨论】:
-
你可能想看看regular expressions,应该可以做你想做的事情。
标签: javascript arrays wildcard
如何在 javascript 中表示字符串中的一系列数字?
例如,
var Ages = "此成员 x 岁";
其中 x 可以是任何数字。
我希望能够在字符串数组中搜索这样的字符串。
【问题讨论】:
标签: javascript arrays wildcard
使用正则表达式,匹配并捕获\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');
}
【讨论】:
Javascript 非常适合连接。
var x = // the age value you are searching for;
var ages = "The member is " + x + " years old";
然后您可以将其包装在一个循环中。
【讨论】: