当前位置: 动力学知识库 > 问答 > 编程问答 >

javascript - Efficient way to convert space separated class list to a Jquery selector?

问题描述:

Is there a fast, reliable way to convert a space-separated class list like:

classOne classTwo classThree

to a selector like:

$('.classOne .classTwo .classThree')

I'm thinking it could done with either a loop that builds a selector string, or a series of regular expressions (one to clean up extra spaces and a second to convert [space] to [space].), but I'd like to know if there’s a built-in way, or something more concise/efficient/clever.

网友答案:

Sure

var klass = "classOne classTwo classThree";
var arr   = klass.split(/\s+/);
var sel   = '.' + arr.join(' .');

$(sel)

FIDDLE

or more directly

$('.' + klass.split(/\s+/).join(' .') )
网友答案:

Simple, use .replace :

var className = 'classOne classTwo classThree';
$(className.replace(/(^ *| +)/g, '$1.'));
网友答案:

How this compact RegEx:

var className = 'classOne classTwo classThree';
$(className.replace(/\b(\w)/g, '.$1'));

This will replace every set of word characters (ex: some classes) in the class list with dot + the word (ex: .some.classes) and then stick the result directly to a jQuery selector.

网友答案:

Based on this other answer,

var selector = className
    .replace(/(?=[^ \w])/g, '\\')   // Escape non-word characters
    .replace(/\b\d/g, '\\00003$&')  // Escape digits at the beginning
    .replace(/(^| +)(?!$| )/g, '.') // Add "." before classes, removing spaces

It works with

  • Untrimmed strings (at the beginning).
  • "Strange" class characters (/, $, *, etc.)
  • Classes which begin with a digit (invalid identifiers)
网友答案:

If you don't like regular expressions:

var className = "classOne classTwo classThree";
var selector = className.split(" ").map(function (_class) {return "." + _class}).join(" ");

You can split className with whitespaces and then use Array.prototype.map to create new array ([".classOne", ".classTwo", ".classThree"]). And then you just join it with whitespaces again.

分享给朋友:
您可能感兴趣的文章:
随机阅读: