JavaScript文字变体搜索

时间:2018-11-29 16:25:23

标签: javascript

除了使用OR(||)表达式使用javascript查找邮政信箱的所有变体之外,还有一种简便的方法吗?

if((Address).indexOf("PO BOX") > -1 || if((Address).indexOf("PO Box") > -1

将从预填充的数据库列中提取地址字段。如果该地址的地址栏中有邮政信箱的任何变体,则需要禁用该选项。

我查看了Mozilla doc,但没有找到我可以使用的任何内容。

5 个答案:

答案 0 :(得分:4)

最好的可能是这样:

const found = Address.toLowerCase().includes("po box");

答案 1 :(得分:2)

将地址转换为小写并搜索值

if((Address.toLowerCase()).indexOf("po box") > -1

答案 2 :(得分:2)

您可以使用以下任何一种方式:

  1. if( Address.test(/po box/gi) )
  2. if( Address.toLowerCase().includes("po box"))
  3. if( Address.toLowerCase().indexOf("po box")) > -1

P.S:-我个人认为第一种方法更干净,更快捷。

答案 3 :(得分:1)

也许只是将Address转换为小写?

const needle = "Po BOx"

if(Address.toLowerCase().indexOf(needle.toLowerCase()) > -1)

OR

if(Address.toLowerCase().includes(needle.toLowerCase()))

答案 4 :(得分:0)

这将是regular expression的合适用例。 以下是一些测试-您可以看到test函数返回一个布尔值,该布尔值指示是否找到了搜索字符串。

第二个i之后的/表示正则表达式搜索将不区分大小写

const regex = /po box/i;

const s1 = "Send to PO Box 1000";
const s2 = "Send to PO box 1000";
const s3 = "Send to po Box 1000";
const s4 = "Send to po box 1000";
const s5 = "Send somewhere else!";

console.log(regex.test(s1));
console.log(regex.test(s2));
console.log(regex.test(s3));
console.log(regex.test(s4));
console.log(regex.test(s5));