0

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);
  }
3
  • Can you share the code you tried so far? Commented Mar 21, 2018 at 3:16
  • How about using filter with includes to select elements that contain your word and then map with replace to remove the word? Commented Mar 21, 2018 at 3:18
  • removes the first instance of the word? if the string was "aaaWord:bbbWord:ccc" would it return "aaabbbWord:ccc" or "aaabbbccc"? Commented Mar 21, 2018 at 3:18

2 Answers 2

2

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

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

Comments

0

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"

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.