如何检测字符串中的单位?

我有一个字符串搜索问题。在我的应用中,我需要在单元内显示一些主题。主题标题如下:


"Unit 1: First lesson"

"Unit 2 and 3: Introduction"

"Unit 4: Exercise"

"Unit 5 and 6: Social Networking"

如您所料,我需要在第1单元中显示第一个主题,并在第2单元和第3单元中显示第二个主题。但是我不知道如何检测主题所属的单元。如果您有什么好主意,请帮助我。


拉莫斯之舞
浏览 175回答 2
2回答

达令说

您可以使用正则表达式提取数字并进行匹配。以下代码创建一个对象数组,其中包含主题标题及其所属的单元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)

白板的微信

您可以使用以下方法检索这些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);});
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript