检查字符串是否以某个字符开头

时间:2013-08-02 18:49:12

标签: javascript string

这是我的代码:

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">'); 

当单词“nes”和/或“snes”在字符串“consoles”中时,它应该输出各自的图标。如果两个控制台都在字符串内,则应显示两个图标。

这显然不起作用,因为“nes”也包含在“snes”中。

那么,有没有办法检查“nes”前面是否有S?

请记住,“nes”可能不是字符串中的第一个单词。

5 个答案:

答案 0 :(得分:3)

看来你最好测试“nes”或“snes”是否出现作为一个单词

if (/\bnes\b/i.test(consoles)) 
  ...

if (/\bsnes\b/i.test(consoles)) 
  ...
这些regular expressions中的

\b字边界i表示它们不区分大小写。

现在,如果你真的想测试你的字符串中是否有“nes”但前面没有“s”,你可以使用

if (/[^s]nes/i.test(consoles))

答案 1 :(得分:1)

检查nes是否在0 ||位置控制台[index - 1]!='s'

答案 2 :(得分:0)

我自己的方法是使用replace(),使用其回调函数:

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;
});

参考文献:

答案 3 :(得分:0)

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

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

答案 4 :(得分:0)

检查字母是否在子字符串之前的基本方法。

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
}

注意:您应该检查以确保不要将索引推出界限...(字符串以“nes”开头会导致错误)