skip to Main Content

I want to compare a string and and array in order to get words or phrases in the string that are present in the array; but I do not want to include words from the string that are not surrounded by whitespaces.

The below code compares userInput and myArray and produced this result: morning,good,good morning,go,he.
You would see that "go" and "he" are also included, although they are not separate words in userInput ("go" is from "good" and "he" is from "hello"). I researched on regular expression but couldn’t figure out how to use them. I need help on how to exclude "go" and "he" from the result.

const userInput = "hello good morning everyone";
const myArray = ["tomorrow", "morning", "good", "good morning", "go", "he"];
const intersect = myArray.filter(word => 
userInput.includes(word)  
);
  
document.write(intersect);

2

Answers


  1. You can instantiate a new RegExp for each phrase in myArray and execute it on the userInput.

    • Make sure wrap the phrase in word-boundaries (b)
    • You could also add a case-ignore flag (i) to ignore case sensitivity
    const
      userInput = "hello good morning everyone",
      myArray   = ["tomorrow", "morning", "good", "good morning", "go", "he"],
      intersect = myArray.filter(phrase =>
                    new RegExp(`\b${phrase}\b`, 'i').exec(userInput));
      
    console.log(intersect); // [ "morning", "good", "good morning" ]

    Here is a an example with with live input evaluation and a debounce:

    const
      inputEl = document.querySelector('#input'),
      phrases = ['tomorrow', 'morning', 'good', 'good morning', 'go', 'he'];
    
    const getIntersections = (input, phrases) =>
      phrases.filter(phrase =>
        new RegExp(`\b${phrase}\b`, 'i').exec(input));
    
    const handleInput = ({ target: { value } }) => {
      const intersections = getIntersections(value, phrases);
      console.log(intersections);
    };
    
    inputEl.addEventListener('input', debounce(handleInput, 250));
    inputEl.dispatchEvent(new CustomEvent('input'));
    
    // Source: https://davidwalsh.name/javascript-debounce-function
    function debounce(func, wait, immediate) {
      let timeout;
      return function() {
        const context = this, args = arguments, later = function() {
          timeout = null;
          if (!immediate) func.apply(context, args);
        };
        const callNow = immediate && !timeout;
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
        if (callNow) func.apply(context, args);
      };
    };
    <input id="input" type="text" value="hello good morning everyone" />
    Login or Signup to reply.
  2. Regex is very powerful, and I highly recommend you become familiar with it. Using a site like regexr.com will help, because you can test things there instantly.

    The b part is a word boundary (with two ‘s because they need to be escaped)

    const userInput = "hello good morning everyone";
    const myArray = ["tomorrow", "morning", "good", "good morning", "go", "he"];
    const intersect = myArray.filter(word => userInput.match(new RegExp("\b" + word + "\b")));
    
    console.log(intersect);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search