Reputation: 11045
I've been using the .indexOf('') > -1
in order to check whether there's a match in a string. The problem that I'm having is that when I'm performing the match on multiple strings, I get a match on the string for both EIFT and EI (since EIFT contains EI), and so the function returns true
for both sentences. What I need is a way for this to only return true for function eIft
if the string is "EIFT", but not for EI
.
My current code is as follows, and I've been trying to think of ways around this but haven't had any success yet.
function eI(mystring){
return mystring.indexOf("EI") > -1
}
function eIft(mystring){
return mystring.indexOf("EIFT") > -1
}
Thanks!
Upvotes: 3
Views: 6930
Reputation: 3134
If you are checking inside a string for you values (e.g. heleilo), then you need to confirm your positive results for the 'EI' check:
function eI(mystrng) {
return mystring.indexOf("EI") != -1 && !eIFt(mystring);
}
This would only work provided they don't both exist in different occurences (e.g. heleileifto). In this case, you have to check the immediate following characters:
function eI(mystring) {
var pos = mystring.indexOf("EI");
if (pos != -1) { // found
var char1 = mystring[pos + 2];
var char2 = mystring[pos + 3];
return char1 !== 'F' && char2 !== 'T';
}
}
OR
function eI(mystring) {
var pos = mystring.indexOf("EI");
if (pos != -1) { // found
return pos != eIFt(mystring); // they won't have the same index
}
}
Upvotes: 1
Reputation: 78920
You can use ===
; that will do an exact match of strings. Use indexOf
only if you're checking whether the string contains another string.
function eI (mystring) {
return mystring === "EI";
}
function eIFt(mystring) {
return mystring === "EIFT";
}
Upvotes: 2