2 回答

TA贡献1821条经验 获得超6个赞
您可以使用正则表达式提取数字并进行匹配。
以下代码创建一个对象数组,其中包含主题标题及其所属的单元
const topics = [
"Unit 1: First lesson",
"Unit 2 and 3: Introduction",
"Unit 4: Exercise",
"Unit 5 and 6: Social Networking"
];
const topicUnits = topics.reduce((acc, t) => {
acc.push({
topic: t,
units: t.split(":")[0].match(/\d/g)
})
return acc;
}, [])
console.log(topicUnits)

TA贡献1883条经验 获得超3个赞
您可以使用以下方法检索这些match():
const units = [
"Unit 1: First lesson",
"Unit 2 and 3: Introduction",
"Unit 4: Exercise",
"Unit 5 and 6: Social Networking"
];
units.forEach(title => {
// Only match on string before the ':'
let unitNumbers = title.substr(0, title.indexOf(':')).match(/([0-9]+)/g);
console.log(title, unitNumbers);
});
添加回答
举报