-4

Let's consider the following string text "I just tried the new burgers in burger land!" and the following array of strings ["eat", "burger", "fries"]

What I want is to know if any of the words of text exist in the array, but in a optimized way... not just with two for-loops...

Any ideas?

Sotiris Kaniras
  • 520
  • 1
  • 12
  • 30

3 Answers3

1

You could do this via regular expression by joining the array to create a string.

RegEx References

Once the RegEx string is created via JavaScript it looks like this (string escaping removed):

\b(?:eat|burger|fries)\b

const str = 'I just tried the new burgers in burger land!'
const arr = ['eat', 'burger', 'fries']

// "\b" This is a word boundary - Allows you to perform a "whole words only" search
// "(?:xxx)" This is a non-capturing group. It's not stored in memory to be referenced later on.
// 'arr.join()' creates the following string: "eat|burger|fries"
console.log(str.match(new RegExp(`\\b(?:${arr.join('|')})\\b`, 'ig')))

If needing to escape regex is a concern, you can do it by escaping special characters. and mapping over the array of words that need to be tested.

const str = 'I just tried the new burgers in burger land!'
const arr = ['eat', 'burger', 'fries', '(']
const esc = s => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')

console.log(str.match(new RegExp(`\\b(?:${arr.map(esc).join('|')})\\b`, 'ig')))
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
1

Well the most optimized way IMO is to have wordsTest as object instead of array so lookup becomes O(1) operation. and than you can use filter to get any matching value.

const test = "I just tried the new burgers in burger land!";
const wordsTest = {"eat":1, "burger":1, "fries":1}

const wordsInString = (test) => test.split(' ').filter(e => wordsTest[e] )

console.log(wordsInString(test))
console.log(wordsInString('No matching words'))
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
0

use Array#Filter and indexOf().

  1. Array#Filter is filter the array based index match in string
  2. use toLowerCase() for match case sensitive string

var a ="I just tried the new burgers in burger land!";
var arr = ["eat", "burger", "fries"];

var res = arr.filter(i=> a.toLowerCase().indexOf(i.toLowerCase()) > -1)
console.log(res)
prasanth
  • 22,145
  • 4
  • 29
  • 53