Reputation: 186
This is my code:
if (consoles.toLowerCase().indexOf("nes")!=-1)
document.write('<img class="icon_nes" src="/images/spacer.gif" width="1" height="1">');
if (consoles.toLowerCase().indexOf("snes")!=-1)
document.write('<img class="icon_snes" src="/images/spacer.gif" width="1" height="1">');
When the words "nes" and/or "snes" are inside the string "consoles", it's supposed to output their respective icon. If both consoles are inside the string, both icons should appear.
This obviously doesn't work, because "nes" is also contained inside "snes".
So, is there a way to check if "nes" is preceded by an S?
Keep in mind that "nes" may not be the first word in the string.
Upvotes: 1
Views: 717
Reputation: 382264
It seems you'd better test if "nes" or "snes" appear as a word:
if (/\bnes\b/i.test(consoles))
...
if (/\bsnes\b/i.test(consoles))
...
\b
in those regular expressions are word boundaries and the i
means that they're case insensitive.
Now if you really want to test if "nes" but not preceded by a "s" is in your string, you may use
if (/[^s]nes/i.test(consoles))
Upvotes: 3
Reputation: 1088
basic way to check if a letter is before the substring.
var index = consoles.toLowerCase().indexOf("nes");
if(index != -1 && consoles.charAt(index-1) != "s"){
//your code here for nes
}
if(index != -1 && consoles.charAt(index-1) == "s"){
//your code here for snes
}
Note: you should do checking to make sure you don't push index out of bounds... (string starts with "nes" will cause error)
Upvotes: 0
Reputation: 3881
"snes".match(/([^s]|^)nes/)
=> null
"nes".match(/([~s]|^)nes/) => nes
Upvotes: 0
Reputation: 253396
My own approach would be to use replace()
, using its callback function:
var str = "some text nes some more text snes",
image = document.createElement('img');
str.replace(/nes/gi, function (a,b,c) {
// a is the matched substring,
// b is the index at which that substring was found,
// c is the string upon which 'replace()' is operating.
if (c.charAt(b-1).toLowerCase() == 's') {
// found snes or SNES
img = image.cloneNode();
document.body.appendChild(img);
img.src = 'http://path.to/snes-image.png';
}
else {
// found nes or NES
img = image.cloneNode();
document.body.appendChild(img);
img.src = 'http://path.to/nes-image.png';
}
return a;
});
References:
Upvotes: 0