正则表达式计数下划线

问题描述 投票:4回答:2

怎么可能通过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

javascript jquery regex
2个回答
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;
© www.soinside.com 2019 - 2024. All rights reserved.