【问题标题】:How do I separate tags in a string如何分隔字符串中的标签
【发布时间】:2022-08-02 22:41:49
【问题描述】:

我目前正在使用 .split 尝试将字符串拆分为不同的 \'tags\'。

let text = \"@yusra is cool @zain @chris is cool\";
const myArray = text.split(\"@\");
console.log(myArray);

上面的代码给出了这个输出:

Array [\"\", \"yusra is cool \", \"zain \", \"chris is cool\"]

预期的输出是:

Array [\"yusra\", \"zain \", \"chris\"]

我该如何修改它以使它做我想做的事。

  • 要么使用正则表达式来获取 @ 和下一个空格之间的所有内容。或者拆分空格,过滤掉所有不以@开头的字符串,最后从名称中删除@。
  • 1.按单词分割,2.检查单词是否以@开头,3.如果是,则删除@并将其添加到myArray

标签: javascript arrays


【解决方案1】:

你可以尝试这样的事情:

const myArray = text.split(" ").filter(s => s.startsWith("@")).map(s => s.substring(1));

【讨论】:

    【解决方案2】:

    将完成任务所需的东西链接在一起。在空间上拆分似乎是一个更好的选择,然后只过滤那些具有“@”和映射以删除“@”的元素。

    let text = "@yusra is cool @zain @chris is cool";
    const myArray = text.split(' ').filter(s => s.startsWith('@')).map(s => s.slice(1))
    console.log(myArray);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-10-14
      • 1970-01-01
      • 1970-01-01
      • 2012-07-29
      • 2013-11-13
      相关资源
      最近更新 更多