0

I fetch the classes of a <div> and save it in a variable.

this classes are following:

item drag drop img-circle _RS _CS ui-draggable ui-droppable ui-draggable-dragging

how can separate the classes that begins with an underline, like: _CS ?

4

3 回答 3

4

您可以使用String.match它们来获得一个数组作为结果:

var classes = "_A drag drop img-circle _RS _CS ui-draggable a-_NASTY ui-xyz _z";
var underscoreClasses = classes.match(/(^| )_\S+/g);
console.log(underscoreClasses); // ["_A", " _RS", " _CS", " _z"]

如果您需要字符串(而不是数组),您可以使用Array.join它来实现:

var classes = "_A drag drop img-circle _RS _CS ui-draggable a-_NASTY ui-xyz _z";
var underscoreClasses2 = classes.match(/(^| )_\S+/g).join("");
console.log(underscoreClasses2); // "_A _RS _CS _z"

在这里演示 JsFiddle

于 2013-07-21T09:02:11.743 回答
1

使用.split.filter

var classes = "item drag drop img-circle _RS _CS ui-draggable ui-droppable ui-draggable-dragging";
classes.split(/\s+/).filter(function(c) { return c[0] === "_"; })
=> ["_RS", "_CS"]
于 2013-07-21T09:07:27.210 回答
0

试试这个代码:

class = "item drag drop img-circle _RS _CS ui-draggable ui-droppable ui-draggable-dragging"
classes = class.split(" ")
underscoreclasses = []
$.each(classes, function(id, value) {
    if (value.slice(0, 1) == "_") {
        underscoreclasses.push(value)
    }
})

console.log(underscroreclasses)

它使用的是split 方法slice 方法

于 2013-07-21T09:01:06.353 回答