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?

3 Answers 3

2

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');
Sign up to request clarification or add additional context in comments.

Comments

1

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)

2 Comments

Not even sure why I didn't think of that... too long looking at the code I think! Thanks a lot, that works. I'll accept the answer when I can.
To be honest, although I've answered your specific question, other answers here are actually closer to what you should be doing. I'm happy to forgo the points in favour of a better answer being promoted.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.