Reputation: 27
I have a string with groups of words in it. How do I substruct the ones with the word green in them?
const str = "apple, cherries, green apples, green, kiwi"
Should return "green, green apples";
Upvotes: 1
Views: 1741
Reputation: 1145
You can use the below code to compile all words that contain an input into a return string.
Comments are included to explain what is happening.
I've also included @orkhanalikhanov 's answer at the bottom, that performs the same function but using in-built JavaScript functions to do it very cleanly in one line.
const str = "apple, cherries, green apples, green, kiwi"; //Define input
function getWords(input,keyWord){ // Take and input and keyword to look for as parameters to a function
stringVar= input.split(","); // Take the input and turn it into an array, with each element being the words between ','
//This is the 'split' in orkhan-alikhanov 's answer
var returnString=""; //create a string to concat all valid words into
//For each word in that array, see if it has the word we are looking for, and if so, add it to the return string with a ',' character at the end
//This is the 'Filter' in orkhan-alikhanov 's answer
for(var i=0 ; i<stringVar.length;i++){
if(stringVar[i].includes(keyWord)){
//This is the 'join' in orkhan-alikhanov 's answer
returnString = returnString+stringVar[i]+",";
}
}
//If we got even 1 result, remove the last ','
if(returnString.length>0){
returnString = returnString.substr(0,returnString.length-1);
}
return returnString;
}
console.log(getWords(str,"green"));
//orkhan-alikhanov's answer that does the same thing
function commentersAnswer(input,keyWord){
return input.split(',').filter(x => x.includes(keyWord)).join(',')
}
console.log(commentersAnswer(str,"green"));
Upvotes: 1