检查字符串前面是否有特定字符

Check if a string is preceded by a certain character

本文关键字:字符 是否 字符串 前面 检查      更新时间:2023-09-26

这是我的代码:

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"可能不是字符串中的第一个单词。

似乎你最好测试"nes"或"snes"是否作为单词出现

if (/'bnes'b/i.test(consoles)) 
  ...
if (/'bsnes'b/i.test(consoles)) 
  ...

这些正则表达式中的'b单词边界,而i表示它们不区分大小写。

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

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

检查nes是否在位置0||consoles[index-1]!='s的

我自己的方法是使用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;
});

参考文献:

  • Node.appendChild()
  • Node.cloneNode()
  • String.charAt()
  • String.replace()

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

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

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

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"开头会导致错误)