简体   繁体   中英

search on string with array with javascript

search on string with array with javascript

i have a string, i need to search on it with array.

for ex.

// that is array what i have
var arr = ['egypt', 'london', 'spain'];

// that is strings what i have
var str = "hello from egypt";
var str2 = "hello from london and spain";

ex. for first string, i need to now if it contain any values from array, and get it.

like : // found one value 'egypt' on str. like : // found two values 'london, spain' on str2.

 // that is array what i have var arr = ['egypt', 'london', 'spain']; // that is strings what i have var str = "hello from egypt"; var str2 = "hello from london and spain"; function search_in_string(_string, _array){ var out_arr=[]; for(var key in _array){ if(_string.indexOf(_array[key]) !=-1){ out_arr.push(_array[key]); } } return out_arr; } console.log(search_in_string(str, arr)); console.log(search_in_string(str2, arr));

You can use includes to see if array elements exist in the string or not
Here's the code that resolves your problem

 // that is array what i have var arr = ['egypt', 'london', 'spain']; // that is strings what i have var str1 = "hello from egypt"; var str2 = "hello from london and spain"; function searchWords(str){ var res=""; for(var i=0;i<arr.length;i++){ if (str.includes(arr[i])){ res+= arr[i] +' ' } } console.log('found one value '+res ) } searchWords(str1); searchWords(str2);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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