0

I've looked high and low for this, with no real idea how to do it now... my scenario:

 var strArray = ['Email Address'];

 function searchStringInArray(str, strArray) {
     for (var j = 0; j < strArray.length; j++) {
        if (strArray[j].match(str)) return j;
     }
     return -1;
 }

 var match = searchStringInArray('Email', strArray);

Email does NOT equal Email Address... however .match() seems to match the two up, when it shouldn't. I want it to match the exact string. Anyone have any idea how I do this?

4

3 回答 3

2

您已经拥有.indexOf()用于您尝试做的同一件事。

所以与其循环,为什么不使用:

 var match = strArray.indexOf('Email');
于 2013-07-04T16:04:09.833 回答
1

String.match将您的参数“电子邮件”视为正则表达式。只需使用==

      if (strArray[j] == str) return j;

String.match 上的 Mozilla 开发网络页面

如果传递了非正则表达式对象 obj,则使用 new RegExp(obj) 将其隐式转换为正则表达式

于 2013-07-04T16:02:25.827 回答
0

或者使用正则表达式

使用^$

var str = "Email";
new RegExp(str).test("Email address")

结果:真

为此:

var str = "Email";
new RegExp("^" + str + "$").test("Email address")

结果:假

于 2013-07-04T16:04:35.883 回答