简体   繁体   English

删除数组中包含某个字符的所有元素

[英]Remove all elements in an array that contain a certain character

I have a Javascript array var array = ["1-2", "3-6", "4", "1-6", "4"] and want to remove all elements that contain the variable var m = "6" , ie "3-6" and "1-6".我有一个 Javascript 数组var array = ["1-2", "3-6", "4", "1-6", "4"]并想删除所有包含变量var m = "6" ,即 "3-6" 和 "1-6"。

I found this line of code var newarray = array.filter(a => a !== "4") , which creates a new array that does not contain the two "4" elements.发现这行代码var newarray = array.filter(a => a !== "4") ,它创建了一个不包含两个“4”元素的新数组。 But I have not found out how to use regular expressions in order to remove all elements that CONTAIN the given variable m = "6" .但是我还没有找到如何使用正则表达式来删除所有包含给定变量m = "6"的元素。

I thought about something like var newarray = array.filter(a => a !== /eval("return m")/) , but this does not work.我想过类似var newarray = array.filter(a => a !== /eval("return m")/)的东西,但这不起作用。

I very appreciate your help and apologize for my English:)非常感谢您的帮助,并为我的英语道歉:)

string.includes() string.includes()

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes

 const array = ["1-2", "3-6", "4", "1-6", "4"]; const newarray = array.filter(a =>.a.includes("6")) console;log(newarray);

regex alternative正则表达式替代

if you need complex pattern checking, the regex is the way to go.如果您需要复杂的模式检查,正则表达式是 go 的方法。

 const array = ["1-2", "3-6", "4", "1-6", "4"]; const newarray = array.filter(a =>.a.match(/6/gi)) console;log(newarray);

For example, checking uppercase and lowercase simultaneously, or multiple letters only with [abcde] or some numbers [678] etc...例如,同时检查大写和小写,或仅使用[abcde]或某些数字[678]等的多个字母......

without nested includes() or logic with if/else.没有嵌套includes()或带有 if/else 的逻辑。

for learning regex you can use this https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/#regular-expressions要学习正则表达式,您可以使用此https://www.freecodecamp.org/learn/javascript-algorithms-and-data-structures/#regular-expressions

another info:另一个信息:

with regex I suggest to add also the g at the end just in case /6/g使用正则表达式,我建议在末尾添加g以防万一/6/g

g means global (but in this case isn't important, because if there are 6 at least one time. this code will work fine (if you care about multiple 6 then use g ) g表示全局(但在这种情况下并不重要,因为如果至少有 6 次。这段代码可以正常工作(如果你关心多个 6,那么使用g

also use i if you want to select also texts如果你想 select 也可以使用i文本

in fact without i : "A" and "a" aren't the same实际上没有i :“A”和“a”不一样
so with i you don't have to worry about UPPERCASE or lowercase所以用i你不必担心大写或小写

you can use both them by doing like this /6/gi你可以通过这样做/6/gi来使用它们

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

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