Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
470 views
in Technique[技术] by (71.8m points)

javascript - 如何查找字符串中是否包含数组值并将其删除?(How do i find if an array value is in a string and remove it?)

I want something like this:

(我想要这样的东西:)

var string = "apple banana";
var array = ["apple", "banana", "orange", "grape"];
for(var i=0;i<array.length;i++){
  if(array[i] is found in (string) {
    remove the value;
  }
}

something like that.

(这样的事情。)

so basically, it would:

(所以基本上,它将:)

  • Declare a string and an array

    (声明一个字符串和一个数组)

  • Iterate through the array

    (遍历数组)

  • If the array[i] value is present exactly in the string, it would remove it

    (如果array [i]值恰好存在于字符串中,它将删除它)

  • The iteration should continue as normal

    (迭代应该照常继续)

In case it still doesnt make sense:

(如果仍然没有意义:)

String is "1 3 bc"

(字符串是“ 1 3 bc”)

Array contains "1", "2","3", "a", "b", "c"

(数组包含“ 1”,“ 2”,“ 3”,“ a”,“ b”,“ c”)

The array should now only contain "2" and "a".

(数组现在应该只包含“ 2”和“ a”。)

  ask by Carson Rueter translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

.filter the array by whether the string does not .includes the substring being iterated over:

(.filter阵列由字符串是否不.includes子串被迭代过:)

 const doFilter = (str, arr) => arr.filter(substr => !str.includes(substr)); console.log( doFilter("apple banana", ["apple", "banana", "orange", "grape"]), doFilter("1 3 bc", ["1", "2","3", "a", "b", "c"]), ); 


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...