我有以下幾點:如何才能使用javascript從字符串中獲取第一個單詞?
var html = document.documentElement;
var class = html.className;
這將返回 「黑NG-範圍」;
我該怎麼做才能讓班級返回第一個單詞?
我有以下幾點:如何才能使用javascript從字符串中獲取第一個單詞?
var html = document.documentElement;
var class = html.className;
這將返回 「黑NG-範圍」;
我該怎麼做才能讓班級返回第一個單詞?
您可以使用
var firstClass = html.className.split(' ')[0]
> "hey there".split(" ")[0]
"hey"
var classes = class.split(" "); // Returns an array
var firstclass = classes[0];
另一個想法是使用正則表達式,如果你能比其他空間的字邊界。
var reg = /(.+?)(?:\s|$)/,
match = html.className.match(reg);
if (match) {
match[1]; // Your match
}
這具有匹配多個單獨空間的附加好處。
編輯:如果您正在使用這個嚴格得到一個HTML元素的所有類和你的目標足夠新的瀏覽器使用classList
像雅各布W¯¯建議。
已經有人問:http://stackoverflow.com/q/3203966/1636522 – leaf