Counting regular expression counts

How can I calculate and find underscorethrough Regex, and then if it exceeds 2 underscores and less than 4 (continuously) do something, and if more than 4 underscores do something else.

$('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>
Run codeHide result

What I'm trying to do is find more than two, less than four underscores, replace with commaelse, if more than four underscores replace nothing.

Now:

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

Purpose:

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

Problem:

The second Regex(more than four underscores) does not work properly.

JSFiddle

+4
source share
2 answers

Here's how you can do this in one regex without multiple regex testand calls 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 
Run codeHide result
+3
const string = "Blah_Blah _ BlahBlah __ test ____ Blah _________________________________________";
const count_underscore_occurrence = (string.match(/_/g) || []).length;
0

Source: https://habr.com/ru/post/1690960/


All Articles