Home > Back-end >  get specific word from a seperated statement by a comma?
get specific word from a seperated statement by a comma?

Time:10-22

I have this string and for example i need to get the the word green eyes from specific string that is sperated by a comma like this example

young lady , beautiful , green eyes , wearing shirt , wearing necklace

I want to get for example green eyes using the word eyes for example

how can I achieve this ?

CodePudding user response:

First split the string, then filter trough the array to find the words that match

const str = "young lady,beautiful,green eyes,wearing shirt,wearing necklace";

const findWord = (word) => str.split(",").filter(x => x.includes(word))

console.log(findWord("green"))

CodePudding user response:

First you need to split those phrases by comma separator using arr.split(',') method.

Then using arr.filter method you can filter array items by given condition.

const input = 'young lady , beautiful , green eyes , wearing shirt , wearing necklace';
const query = 'eyes';

const phrases = input.split(',');
const filteredPhrases = phrases.filter(phrase => phrase.includes(query));

console.log(filteredPhrases); // output: [ " green eyes " ]

CodePudding user response:

If you are looking for a function version answer.

const string =
  "young lady , beautiful , green eyes , wearing shirt , wearing necklace";

const getSpecificWord = (string, word) => {
  let selectedItem = string.split(",").find((s) => s.includes(word));
  return selectedItem;
};

const result = getSpecificWord(string, "eye");

console.log(result)

  • Related