Pavel Valeriu Pavel Valeriu - 2 months ago 6
Javascript Question

How to find certain words in string?

I have an array of strings and each string contains a key word plus a number (the number value is different, only the key word is constant) and I want to know how can I get the word and also the number...see the example below:

var keyWords = ["data","action","type"];

var stringArray = ["set data4 to custom value '1'",
"set data110 to custom value '2'",
"overwrite value of action1023 with new value",
"set type23 to custom value '10'",
"overwrite value of action13 with text",
"set type48 to custom value '7'"]


And the response should be like this:

var response = ["data4","data110","action13","type23","action1023","type48"];


This is what I've managed to do:

var response = [];
for(var j=0; j<keyWords.length; j++) {
for(var i=0; i<stringArray.length; i++) {
if(stringArray[i].indexOf(keyWords[j]) !== -1) {
response.push(keyWords[j]);
}
}
}


But it only returns me the exact key words, without numbers..

response = [data, data, action, action, type, type]

Answer

This code does the job

var keyWords = ["data","action","value","type"];

var stringArray = ["set data4 to custom value '1'",
               "set data110 to custom value '2'",
               "overwrite value of action1023 with new value",
               "set type23 to custom value '10'",
               "overwrite value of action13 with text",
               "set type48 to custom value '7'"]

var response = [];

for(var i = 0; i < stringArray.length; ++i){
    for(var j = 0; j < keyWords.length; ++j){
        if((index = stringArray[i].indexOf(keyWords[j])) !== -1){
            splittedStr = stringArray[i].substring(index,         stringArray[i].length).split(' ', 1);
            response.push(splittedStr[0]);
        }
    }
}
console.log(response);