2017-12-18 94 views
4

它怎麼可能算找到underscore通過Regex那麼,如果它是高於2下劃線和小於4 (連續)做一些,如果超過4個下劃線做別的事情正則表達式計數強調

$('div').text(function(i, text) { 
 
    var regex2 = /_{2,4}/g; 
 
    var regex4 = /_{4,999}/g; 
 
    //var regexLength = text.match(regex).length; 
 

 
    if (regex2.test(text)) { 
 
    return text.replace(regex2, '،'); 
 
    } else if (regex4.test(text)) { 
 
    return text.replace(regex4, ''); 
 
    } 
 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div> 
 
    Blah_Blah _ BlahBlah __ test ____ Blah _________________________________________ 
 
</div>

我想要做的是,找到兩個以上的,不到四年不斷強調,與comma人換掉,如果超過四個下劃線與nothing取代。

目前:

<div> 
    Blah_Blah _ BlahBlah __ test ____ Blah _________________________________________ 
</div> 

目標:

<div> 
    Blah_Blah _ BlahBlah , test , Blah 
</div> 

問題:

第二regex(四個以上的下劃線)不按預期工作。

JSFiddle

+2

'_ {2, 4}'匹配2,3或4個下劃線。 '_ {4,999}'匹配4到999'_'s。你的模式重疊。 –

+1

首先檢查'4,999',然後在else子句中檢查'2,4'。 – anubhava

+0

請參閱https://jsfiddle.net/ckrk0o95/2/,在此之後? 'return text.replace(/(_ {5,999})| _ {2,4}/g,function($ 0,$ 1){return $ 1?'':',';})' –

回答

3

這裏是你如何能在一個單一的正則表達式做到這一點無需多次的正則表達式testreplace電話:

var str = 'Blah_Blah _ BlahBlah __ test ____ Blah _________________________________________' 
 
var r = str.replace(/_{2,}/g, function(m) { return (m.length>4 ? '' : ',') }) 
 
console.log(r) 
 

 
//=> Blah_Blah _ BlahBlah , test , Blah

0
const string = "Blah_Blah _ BlahBlah __ test ____ Blah _________________________________________"; 
const count_underscore_occurrence = (string.match(/_/g) || []).length;