使用特定子字符串获取类名的正则表达式 [英] Regular expression to get class name with specific substring

查看:90
本文介绍了使用特定子字符串获取类名的正则表达式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要在javascript中使用正则表达式,它将从空格分隔字符串列表中获取具有特定子字符串的字符串。

I need a regular expression in javascript that will get a string with a specific substring from a list of space delimited strings.

例如,我有;


  • widget util cookie i18n-username

I希望能够只返回i18n-username。

I want to be able to return only i18n-username.

如何

推荐答案

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

这篇关于使用特定子字符串获取类名的正则表达式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆