1

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";

2
  • 8
    str.split(',').filter(x => x.includes('green')).join(',') Commented Jun 14, 2021 at 21:18
  • 1
    @OrkhanAlikhanov Beautiful answer! I've included yours in my answer below if that's cool? Commented Jun 14, 2021 at 21:31

1 Answer 1

1

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"));

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.