![](/img/trans.png)
[英]How can I pick out the first letter of the first word and then the second word from a string?
[英]How can I get the first word only out of a string with javascript?
我有以下內容:
var html = document.documentElement;
var class = html.className;
返回“ black ng-scope”;
我怎樣才能使班級只返回第一個單詞?
您可以使用
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元素的所有類,並且您定位到足夠新的瀏覽器,則使用建議的Jakob W這樣的classList
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.