Search code examples
javascriptregexstringsplitstring-matching

Optamise way to match a word in javascript?


I am trying to match word in javascript if i use 'if' and 'split' method each time I stuck in the case-sensetive.

If I am using regExp then if a part of word matched it returned true (i.e : hii , /hi/). What I do do to match case-insensitive and whole word should be match.

Code of the regEx

async function matchOne(str ,mtc) {
  let returnval;
  let words = str.split(' ')
  await words.forEach(word => {
    if (word.match(mtc)) {
      returnval = true;
      return true
    }
  });
  if (returnval === true) {
    return true;
  } else {
    return false;
  }
}
matchOne(string,regEx)

Code of the if statement

async function matchOne(str ,mtc) {
  let returnval;
  let words = str.split(' ')
  await words.forEach(word => {
    if (word == mtc) {
      returnval = true;
      return true
    }
  });
  if (returnval === true) {
    return true;
  } else {
    return false;
  }
}

matchOne(string,string)

Solution

  • Hey there check out the code snippet below hopefully that should help you

    const str = 'arya stark';
    
    // The most concise way to check substrings ignoring case is using
    // `String#match()` and a case-insensitive regular expression (the 'i')
    str.match(/Stark/i); // true
    str.match(/Snow/i); // false
    

    In case you want to use forEach then consider converting the string to lowercase and search for a lowercase version of the word as shown below

    str.toLowerCase().includes('Stark'.toLowerCase()); // true
    str.toLowerCase().indexOf('Stark'.toLowerCase()) !== -1; // true