2013-08-02 99 views
1

前面这是我的代码:检查字符串是否是由某个字符

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

当词“网元”和/或“SNES”是字符串里面的“游戏机”,它应该输出自己的各自的图标。如果两个控制台都在字符串内,则应显示两个图标。

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

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

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

回答

3

看来你最好测试,如果“网元”或“SNES”的出现作为一个字

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

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

这些regular expressions\b字边界i意味着他们不区分大小写。

现在,如果你真的想测试,如果“网元”,而不是由一个“S”开头是你的字符串,你可以使用

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

答案是使用正则表达式。 '\ b'是分词 – bozdoz

1

检查,如果网元是位置0 ||控制台[指数 - 1] = 'S'

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

参考文献:

0

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

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

+0

请解释一下为什么会有效,而不仅仅是给出答案。 – ArtB

+0

这将给任何有nes(但不是snes)的行 –

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 
} 

注意:你应该做的检查,以确保你不推索引越界...(字符串“网元”启动会导致错误)

相关问题