【问题标题】:how to push a words into an array in javascript如何在javascript中将单词推送到数组中
【发布时间】:2021-02-04 11:39:46
【问题描述】:

我想在单词之间进行拆分,但不在“@%5967411b349:Jean leo%”标签内。

如何解决?

let title = "Hello everyone @%5967411b349:Jean leo% and @%5995006d0d:David Leong% wish you have a good day with <audi <samsung and #canon";


const formatTitle = (title) => {
    const results = []
    title.trim().split(" ").map(title => {
        if (title.indexOf("#") === 0) {
            results.push(title)
            results.push(" ")
        }
        else if (title.indexOf("<") === 0) {
            results.push(title)
            results.push(" ")
        }
        else if((title.indexOf(title)) === 0)
        {
            let userTag = title.replace(/[@%]*/g, '').split(':');
            results.push(title)
            results.push(" ")
        }
        else {
            results.push(`${title} `)
            results.push(" ")
        }
    })
    return results
};

formatTitle(title)

预期输出:大家好@Jean leo @David Leong 祝您与 有美好的一天

【问题讨论】:

    标签: javascript arrays reactjs string ecmascript-6


    【解决方案1】:

    我想你正在寻找这个

    let input = "Hello everyone @%5967411b349:Jean leo% and @%5995006d0d:David Leong% wish you have a good day with <audi <samsung and #canon";
    
    const userTag = (str) => {
        str = str.replace(/\@\%(.*?):(\w+)\s+(\w+)\%/g, '@$1:$2_$3');
        let groups = str.match(/[@#<]?\w*:?\w+/g)
                        .map(item => (item.indexOf('@') > -1) ? item.replace('_', ' ') : item);
        console.log(groups);
    }
    
    userTag(input);

    【讨论】:

      【解决方案2】:

      这可能会让人感到困惑,但正则表达式可以通过替换功能很好地实现这一点。

      let string = "Hello everyone @%5967411b349:Jean leo% and @%5995006d0d:David Leong% wish you have a good day with <audi <samsung and #canon";
      
      console.log(string.replace(/(@%[0-9a-z]{1,}:)([a-zA-Z\s]{1,})(%)/g, "@$2"));

      粗略的代码不是最终的解决方案,但可能是一个想法的起点。 https://regexr.com/5lns0 将在这里演示正则表达式当前的工作方式。

      【讨论】:

      • 这很好,但请您按照我的代码执行此操作。因为我需要在“results.push()”中推送一些东西。我应该使用 insted of title.trim().split(" ").map({....}) 什么?
      【解决方案3】:

      我使用正则表达式来解决这个问题。你可以检查一下。

      let title = "Hello everyone @%5967411b349:Jean leo% and @%5995006d0d:David Leong% wish you have a good day with <audi <samsung and #canon";
      title = title.replace(/@\W\w+:(\w+\s\w+)%/g, "@$1");
      
      
      const titleArray = title.match(/(#?<?\w+)|(\@\w+\s\w+)/g);
      
      console.log(titleArray);

      【讨论】:

      • 这很好,但请您按照我的代码执行此操作。因为我需要在“results.push()”中推送一些东西。我应该使用 insted of title.trim().split(" ").map({....}) 什么?
      • @SilentStorm 请检查一下,我现在返回了一个数组。
      • 非常感谢您的帮助,但您能否编辑您的正则表达式一点点 cz 输出将是 [ ......,"good","day","with","
      • @SilentStorm 请立即查看。如果它解决了您的问题,那么请对此进行投票并将此答案设置为已接受。这也将帮助其他人找到解决方案。
      猜你喜欢
      • 2022-11-06
      • 2020-02-03
      • 1970-01-01
      • 2021-12-05
      • 1970-01-01
      • 2017-12-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多