简体   繁体   中英

How to return multiple values of String that are present in an array

I have an array.

eg. var ratio = ["Net Sales", "Total Sales", "Profit", "Day's Sale", "Average", "Sum"]

I want to return all the values that are present in this array when compared with the string.

String eg:

var str = "ABC of [Net Sales = Total Sales (Profit)]"

My final output should be: ["Net Sales", "Total Sales", "Profit"]

I have tried to use some() but it only returns a boolean.

var stringIncludesItem = ratio.some(item => str.includes(item));

.some() only returns true when at least one of the items returns true for the condition imposed. .filter() filters out (removes, but not from the original array) elements that do not return true for the condition imposed.

var ratio = ["Net Sales", "Total Sales", "Profit", "Day's Sale", "Average", "Sum"];
var str = "ABC of [Net Sales = Total Sales (Profit)]";
var stringIncludesItem = ratio.filter(item => str.includes(item));

Use filter :

 var ratio = ["Net Sales", "Total Sales", "Profit", "Day's Sale", "Average", "Sum"]; var str = "ABC of [Net Sales = Total Sales (Profit)]"; var stringIncludesItem = ratio.filter(item => str.includes(item)); console.log(stringIncludesItem)

You can use a regex to grab the strings you need:

 const arr = ["Net Sales", "Total Sales", "Profit", "Day's Sale", "Average", "Sum"]; const str = "ABC of [Net Sales = Total Sales (Profit)]"; const regex = new RegExp(arr.join('|'), 'g'); console.log(str.match(regex));

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