繁体   English   中英

如何从字符串数组中删除“:”和“,”和“':”?

[英]how to remove ":" and "," and "':" from array of strings?

我有一个非常基本的问题,而且我是字符串的新手。 在我的代码中,我有大量单词,其中大部分包含我从用户当前网页(这是一个 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)
   })

使用正则表达式进行替换,替换后拆分字符串

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

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

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

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

 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对象过滤掉重复项

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM