2017-05-03 29 views
0

我正在根據某些條件從HTML元素中移除類。這是我的正則表達式:從正則表達式js中的匹配模式中刪除空格

elem.className = elem.className.replace(/shake|progress|done/g, ''); 

但這種模式有一個問題,如果有人增加了一個班說shaker,這也將被刪除。所以我改變了模式:

elem.className = elem.className.replace(/(^|\s)shake(\s|$)|(^|\s)progress(\s|$)|(^|\s)done(\s|$)/g, ''); 

現在只刪除,如果整個單詞相匹配。但現在它消除了單詞周圍的空間。我不知道如何解決這個問題。請幫我解決一下這個。

+1

這不是正則表達式的工作。與['classList'](https://developer.mozilla.org/en-US/docs/Web/API/Element/classList)互動。 –

+0

你能舉出一個前後準確的例子,意思是應用正則表達式之前和之後的字符串 –

+3

德里克有正確的答案;但是將整個單詞與正則表達式匹配的技術無論如何都值得一提:請看[單詞邊界錨點](http://www.regular-expressions.info/wordboundaries.html)。 –

回答

3

這不是一個正則表達式的工作。請與classList互動。

elem.classList.remove("shake", "progress", "done"); // removes all 3 class values 
+0

謝謝,這將起作用。但是,也許在其他情況下,我需要匹配整個單詞。什麼應該是正則表達式模式。 –

0

classList.remove是最好的方法。

這回答了你的問題:

<!DOCTYPE html> 
<html> 
<head> 
    <meta charset="utf-8"> 
    <meta name="viewport" content="width=device-width"> 
    <title>JS Bin</title> 
</head> 
<body> 
    <div id="tt" class="eins zwei drei meins">ABC</div> 
</body> 
    <script> 
    tt.className=tt.className.replace(/\beins|zwei|drei/g, ''); 
    </script> 

</html> 
0

我與其他人同意,classList是去這裏的路,但是如果你想匹配整個單詞,你可以做到這一點。拆分className在空間上並過濾掉要刪除的類列表中的任何項目:

const classes = elem.className.split(' '); 
const remove = ['shake', 'progress', 'done']; 

elem.className = classes.filter(cls => !remove.includes(cls)).join(' ');