且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

使用特定子字符串获取类名的正则表达式

更新时间:2023-11-14 09:43:10

您可以使用以下功能,使用正则表达式匹配由空格或行的开头或结尾包围的字符串。但是如果打算使用它们,你必须要小心准备任何正则表达式特殊字符,因为搜索参数将被解释为字符串而不是RegExp文字:

You could use the following function, using a regex to match for your string surrounded by either a space or the beginning or end of a line. But you'll have to be careful about preparing any regular expression special characters if you plan to use them, since the search argument will be interpreted as a string instead of a RegExp literal:

var hasClass = function(s, klass) {
  var r = new RegExp("(?:^| )(" + klass + ")(?: |$)")
    , m = (""+s).match(r);
  return (m) ? m[1] : null;
};

hasClass("a b c", "a"); // => "a"
hasClass("a b c", "b"); // => "b"
hasClass("a b c", "x"); // => null

var klasses = "widget util cookie i18n-username";
hasClass(klasses, "username"); // => null
hasClass(klasses, "i18n-username"); // => "i18n-username"
hasClass(klasses, "i18n-\\w+"); // => "i18n-username"

正如其他人所指出的那样,你也可以简单地使用拆分和indexOf:

As others have pointed out, you could also simply use a "split" and "indexOf":

var hasClass = function(s, klass) {
  return (""+s).split(" ").indexOf(klass) >= 0;
};

但请注意,indexOf函数最近才引入JavaScript,所以对于旧版浏览器你可能必须自己实现它。

However, note that the "indexOf" function was introduced to JavaScript somewhat recently, so for older browsers you might have to implement it yourself.

var hasClass = function(s, klass) {
  var a=(""+s).split(" "), len=a.length, i;
  for (i=0; i<len; i++) {
    if (a[i] == klass) return true;
  }
  return false;
};

请注意,对于大多数浏览器而言,split / indexOf解决方案可能更快(尽管不是全部)。此 jsPerf基准测试显示哪种解决方案对各种浏览器更快 - 尤其是,Chrome必须有一个非常好的正则表达式引擎!

Note that the split/indexOf solution is likely faster for most browsers (though not all). This jsPerf benchmark shows which solution is faster for various browsers - notably, Chrome must have a really good regular expression engine!