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?
You already have .indexOf() for the same thing you are trying to do.
So rather than looping over, why not use:
var match = strArray.indexOf('Email');
String.match
is treating your parameter 'Email' as if it is a regular expression. Just use ==
instead:
if (strArray[j] == str) return j;
From the Mozilla Development Network page on String.match :
If a non-RegExp object obj is passed, it is implicitly converted to a RegExp by using new RegExp(obj)
Alternatively using RegExp
Use ^
and $
var str = "Email";
new RegExp(str).test("Email address")
Result: true
And for this:
var str = "Email";
new RegExp("^" + str + "$").test("Email address")
Result: false
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.