Stormkyleis
Stormkyleis

Reputation: 186

Check if a string is preceded by a certain character

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

Answers (5)

Denys S&#233;guret
Denys S&#233;guret

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

Caleb
Caleb

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

ilan berci
ilan berci

Reputation: 3881

"snes".match(/([^s]|^)nes/)
=> null

"nes".match(/([~s]|^)nes/) => nes

Upvotes: 0

David Thomas
David Thomas

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

TakeMeAsAGuest
TakeMeAsAGuest

Reputation: 995

check if nes is in position 0 || consoles[index - 1] != 's'

Upvotes: 1

Related Questions