如何通过Regex
计数和查找underscore
,如果它高于 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
以下是如何在单个正则表达式中执行此操作,而无需多个正则表达式test
和replace
调用:
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
const string = "Blah_Blah _ BlahBlah __ test ____ Blah _________________________________________";
const count_underscore_occurrence = (string.match(/_/g) || []).length;