为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

拉莫斯之舞 2021-04-25 12:13:52
我有一个字符串搜索问题。在我的应用中,我需要在单元内显示一些主题。主题标题如下:"Unit 1: First lesson""Unit 2 and 3: Introduction""Unit 4: Exercise""Unit 5 and 6: Social Networking"如您所料,我需要在第1单元中显示第一个主题,并在第2单元和第3单元中显示第二个主题。但是我不知道如何检测主题所属的单元。如果您有什么好主意,请帮助我。
查看完整描述

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)


查看完整回答
反对 回复 2021-05-06
?
白板的微信

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);

});


查看完整回答
反对 回复 2021-05-06
  • 2 回答
  • 0 关注
  • 174 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信