如果字符串与javascript中的regex匹配,请从数组中删除它们

Remove strings from an array if they match regex in javascript

本文关键字:数组 删除 字符串 javascript 中的 匹配 regex 如果      更新时间:2023-10-09

我有一个包含不同字符串的数组。我想删除字符串中与正则表达式匹配的所有非单词。

myarray = ['I want to play football , not watch it yeah:', 'Leeds: play the / worse football']
myregex = /'W+'s/gi

我想删除所有与正则表达式匹配的非单词,但保持字符串不变,包括空格。

  newarray = ['I want to play football not watch it yeah', 'Leeds play the worse football']

我不知道该怎么做。

听起来像是要使用字符串replace:来map数组

myregex = /'W+'s/gi;
newarray = myarray.map(function (str) {
  return str.replace(myregex, '');
});

使用此RegEx:

('s[^'w ]|[^'w ])

RegExr上的实时演示

您可以在使用.replace()的阵列上使用它,如下所示:

MyRegex = /('s[^'w ]|[^'w ])/gi;
NewArray = MyArray.map(function(string) {
    return string.replace(MyRegex, '')
})

MyArray = ['I want to play football , not watch it yeah:', 'Leeds: play the / worse football']
MyRegex = /('s[^'w ]|[^'w ])/gi
NewArray = MyArray.map(function(string) {
    var NewString = string.replace(MyRegex, '')
    document.write(NewString + '<br>')
    return NewString
})