如何在JS中进行搜索

我有一个像下面这样的字符串。

const a = "The school is big."

我想进行搜索。

function searching(q){
    ...
}

// searching(the) -> true
// searching(e s) -> true
// searching(oolis) -> true
// searching(the big) -> false        

您能为这种情况推荐一些解决方案吗?

tao888888 回答:如何在JS中进行搜索

如果使用.replace()从输入字符串和搜索字符串中删除空格,并使用toLowerCase()将其都转换为小写,则可以使用.includes()方法检查是否您的搜索字符串在输入字符串之内:

const a = "The school is big.";

function searching(str,q) {
  const str_no_space = str.replace(/\s+/g,'').toLowerCase();
  const q_no_space = q.replace(/\s+/g,'').toLowerCase();
  return str_no_space.includes(q_no_space);
}

console.log(searching(a,"the")); // -> true
console.log(searching(a,"e s")); // -> true
console.log(searching(a,"oolis")); // -> true
console.log(searching(a,"the big")); // -> false

,

使用includes()toUpperCase()进行不区分大小写的字符串比较。

const a = "The school is big."

function searching(q){
   return a.toUpperCase().includes(q.toUpperCase());
}

console.log(searching('the'));
console.log(searching('e s'));
console.log(searching('oolis'));
console.log(searching('the big'));

本文链接:https://www.f2er.com/3168902.html

大家都在问