Optamise 方法来匹配 javascript 中的单词?

Optamise way to match a word in javascript?

如果我使用 'if''split'[=25=,我将尝试匹配 javascript 中的单词] 方法每次我卡在 case-sensitive.

如果我使用正则表达式,那么如果单词的一部分匹配,它会返回 true (即:hii,/hi/)。我所做的匹配不区分大小写和整个单词应该匹配。

正则表达式代码

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)

if 语句的代码

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)

嘿,看看下面的代码片段,希望它能帮到你

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

如果您想使用 forEach,请考虑将字符串转换为小写并搜索单词的小写版本,如下所示

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

我认为这对你有用。

为清楚起见,我删除了一些代码。

function matchOne(str ,mtc) {
  let returnval;
  let words = str.split(' ')
  words.forEach(word => {
    console.log(word)
    if (word.toLower().match(mtc)) {
      console.log('Found word:'+ word + ' regexp='+mtc)
      returnval = true;
    } else console.log('NOT Found word:'+ word  + ' regexp='+mtc)
  });
  return returnval;
}
matchOne('Hello world','he'); // true
matchOne('Hello world','He'); // true

至于Upper/Lower个案。您需要决定输入和正则表达式应该是上部还是下部或其他。 只需将 .toLower() 附加到您的论点即可。

示例:word.toLower().match(mtc)

您可以使用正则表达式匹配字符串并使用全局和不区分大小写的标志

let str = 'this string have Capital and no capital';

let match = str.match(/capital/gi);

console.log(match);

  1. 正则表达式匹配

考虑到正则表达式将匹配整个字符串,没有必要将字符串拆分为单词。

const regex = /hello/gi
const string = "hello world"
console.log(!!string.toLowerCase().match(regex)); // true

const string2 = "HELLO WORLD"
console.log(!!string2.toLowerCase().match(regex)); // true

const string3 = "WORLD ABC"
console.log(!!string3.toLowerCase().match(regex)); // false

此处i使正则表达式匹配不区分大小写。 !!用于将我们匹配后收到的数组转换为布尔值。

  1. 字符串匹配

您可以进一步简化和清理您的代码 - 就像这样。 我们按单词拆分字符串。这将为我们提供一系列单词。现在我们检查是否至少有一个词与您匹配。

function matchOne(string, mtc) {
  return string.split(' ').some(word => word.toLowerCase() === mtc.toLowerCase())
}

console.log('hello world', 'hello'); // true
console.log('world abc', 'hello'); // false