如何从 JavaScript 中的字符串中提取特定数据?
How to extract specific data from a string in JavaScript?
我的字符串将始终以以下格式返回,其中数字代表我需要定位的不断变化的变量:
params:string = "a random description here followed by a space and then this #gruser4upload #gruser15cat #gruser23camp"
如何提取数字?
鉴于上面的字符串,我需要实现以下结果:
upload = 4
cat = 15
camp = 23
我试过使用如下方法,但由于 #gruser
存在于我的所有三个目标中,所以它不起作用。
let upload = params.substring(
params.lastIndexOf("#gruser") + 1,
params.lastIndexOf("upload")
);
使用正则表达式捕获数字后跟字母字符,然后提取每组:
const params = "a random description here followed by a space and then this #gruser4upload #gruser15cat #gruser23camp";
let match;
const re = /(\d+)([a-z]+)/gi;
while (match = re.exec(params)) {
console.log(match[1] + ' : ' + match[2]);
}
我的字符串将始终以以下格式返回,其中数字代表我需要定位的不断变化的变量:
params:string = "a random description here followed by a space and then this #gruser4upload #gruser15cat #gruser23camp"
如何提取数字?
鉴于上面的字符串,我需要实现以下结果:
upload = 4
cat = 15
camp = 23
我试过使用如下方法,但由于 #gruser
存在于我的所有三个目标中,所以它不起作用。
let upload = params.substring(
params.lastIndexOf("#gruser") + 1,
params.lastIndexOf("upload")
);
使用正则表达式捕获数字后跟字母字符,然后提取每组:
const params = "a random description here followed by a space and then this #gruser4upload #gruser15cat #gruser23camp";
let match;
const re = /(\d+)([a-z]+)/gi;
while (match = re.exec(params)) {
console.log(match[1] + ' : ' + match[2]);
}