Dave Merwin
Dave Merwin

Reputation: 1412

In javascript, Find an item in an array that contains a string and then return that item

I have an array of strings.

I want to search in that array for and string that contains a specific string.

If it's found, return that string WITHOUT the bit of the string we looked for.

So, the array has three words. "Strawbery", "Lime", "Word:Word Word"

I want to search in that array and find the full string that has "Word:" in it and return "Word Word"

So far I've tried several different solutions to no avail. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes looks promising, but I'm lost. Any suggestions?

Here's what I've been trying so far:

var arrayName = ['Strawberry', 'Lime', 'Word: Word Word']
function arrayContains('Word:', arrayName) {
    return (arrayName.indexOf('Word:') > -1);
  }

Upvotes: 0

Views: 67

Answers (2)

Cybernetic
Cybernetic

Reputation: 13334

Use .map:

words_array = ["Strawbery", "Lime", "Word:Word Word"]


function get_word(words_array, search_word) {
  res = '';
  words_array.map(function(word) {
  if(word.includes(search_word)) {
  res = word.replace(search_word, '')
  }
  })
  return(res)
  }

Usage:

res = get_word(words_array, 'Word:')

alert(res) // returns "Word Word"

Upvotes: 0

Eddie
Eddie

Reputation: 26844

You can use find to search the array. And use replace to remove the word.

This code will return the value of the first element only.

let arr = ["Strawbery", "Lime", "Word:Word Word"];
let search = "Word:";

let result = (arr.find(e => e.includes(search)) || "").replace(search, '');

console.log(result);

If there are multiple search results, you can use filter and map

let arr = ["Strawbery", "Word:Lime", "Word:Word Word"];
let search = "Word:";

let result = arr.filter(e => e.includes(search)).map(e => e.replace(search, ''));

console.log( result );

Upvotes: 2

Related Questions