【问题标题】:how to remove ":" and "," and "':" from array of strings?如何从字符串数组中删除“:”和“,”和“':”?
【发布时间】:2020-11-05 13:37:55
【问题描述】:

我有一个非常基本的问题,而且我是字符串新手。 在我的代码中,我有大量的单词,其中大部分包含我从用户当前网页获取的字母(这是一个 chrome 扩展)。有时我会得到想要从该字符串中删除的数字、逗号和分号。如何完全删除它们?

我已经在我的 Javascript 中尝试过这个 -

// p is a large string and words is the array of each word from that string formed by separating each form by ' ' 

   let words = p.split(' ');
   words.forEach(word => {
      console.log(word)
      let arr = word.replace('[,]+', '')
      console.log(arr)
   })

【问题讨论】:

  • 先替换再拆分成单词不是更方便吗?

标签: javascript regex string replace


【解决方案1】:

使用regular expression 进行替换,替换后拆分字符串

let sentence = "Foo bar, etc. and so: on. Number2";
console.log(sentence.replace(/[.,:0-9]/g, "").split(" "));

【讨论】:

  • @AbishekKumar 是的,如果你用谷歌搜索“正则表达式”,至少有一百个。
【解决方案2】:

您可以简单地分割空格和所有不需要的字符:

var sentence = "the quick, brown fox; jumped (over) the fence."
var seen = {};
var result = sentence
    .split(/[ ,;\(\)\.]+/)
    .sort()
    .filter(Boolean)
    .filter((word) => {
        if(seen[word]) {
            return false;
        }
        seen[word] = 1;
        return true;
    });
console.log('result: ' + result.join(', '));

控制台输出: result: brown, fence, fox, jumped, over, quick, the

解释:

  • .split(/[ ,;\(\)\.]+/) - 分割空格和所有不需要的字符
  • .sort() - 对数组进行排序
  • .filter(Boolean) - 删除空数组项
  • .filter((word) => {...}) - 使用 seen 对象过滤掉重复项

您没有要求排序和过滤,但我认为这可能对您的情况有用。

【讨论】:

    【解决方案3】:

    您可以使用正则表达式从字符串中删除所有字符。

    var word = word.replace(/[^\w\s]/gi, '')
    

    【讨论】:

    • 下划线算作\w,我不认为OP希望删除所有特殊字符,但保留下划线。
    • 另外,[\W\S] 做同样的事情,没有否定。
    • 最后,i 标志在您的代码中没有任何作用。
    猜你喜欢
    • 2021-01-29
    • 1970-01-01
    • 2018-09-27
    • 2016-06-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-08
    相关资源
    最近更新 更多