user1754738
user1754738

Reputation: 347

Find Array Values in String

I’d like to capture whether a value is contained in a string. I have a finite list of values to be matched against a comma separated variable length string that could be 400 characters long. Any occurrences of the string will only appear once, there won’t be any duplicates nor will there be two instances of a static list item in the string, e.g., the string will never contain both “Poor” and “Ultimate”.

Static List of Items

Poor Fair Good Better Best Ultimate

String to search against

Cake,Good,Pickles,System,Tires

I realize I can use indexOf and a bunch of IF statements, but I’m wondering if there’s a better of doing this, like assigning my static list to an array

var myList=new Array [“Poor”, “Fair”, “Good”, “Better”, “Best”, “Ultimate”];

I don’t know how to loop through the array and the string to return the value found, e.g., “Good” in this example. What is the best way of doing this – best defined as most efficient, fastest and easiest to maintain (assuming those aren’t contradictions)?

Thanks

Upvotes: 0

Views: 80

Answers (2)

Romain
Romain

Reputation: 321

Depending of your needs, you can use the array functions forEach or every :

var myList=['Poor', 'Fair', 'Good', 'Better', 'Best', 'Ultimate'];
var myString = "Cake,Good,Pickles,System,Tires";
var valContainedInString = [];

myList.forEach(isInString);


function isInString(pVal, pIndex, pArray) {
    if(myString.indexOf(pVal) >= 0) {
        valContainedInString.push(pVal);
    }
}


for(var i = 0; i < valContainedInString.length; i++) {
    console.println(valContainedInString[i]);
}

This will output : "good".

More info : foreach every

Upvotes: 1

DontVoteMeDown
DontVoteMeDown

Reputation: 21465

Yes, you're in the right way, in my opinion. Look:

var myList= ["Poor", "Fair", "Good", "Better", "Best", "Ultimate"];
var stringList = "Cake,Good,Pickles,System,Tires";

for (var i = 0; i < myList.length; i++)
{
    if (stringList.indexOf(myList[i]) > -1)
    {
        window.alert("Contains: " + myList[i]);
        break;
    }
}

Demo.

If you're secure that those values will match and you don't need any validation of that string in the list, that simple loop - in vanilla js - will work. Fast, efficient and easy to maintain.

Upvotes: 2

Related Questions