我需要计算多次出现两个字符之间的字符数

时间:2018-02-08 00:57:18

标签: javascript jquery regex

我需要计算<>之间文本的长度在长输入字符串中,<>将由用户多次重复。

   var Msg1 = "The lengh of <this> has to be calculated. And also <of this>. And of <this>";
   var regex = /<([^>]*)>/g;
   var IntExam = regex.exec(Msg1);
   var IntExL = IntExam[1].length;
   alert(IntExL);

但是,当我想获得&lt;&gt;所包含的所有文字的长度时,我只会得到错误的长度。

1 个答案:

答案 0 :(得分:0)

使用循环:

var Msg1 = "The lengh of <this> has to be calculated. And also <of this>. And of <this>";
var regex = /<([^>]*)>/g;
var totalLength = 0;
do {
  var IntExam = regex.exec(Msg1);
  if(!IntExam) break;
  var IntExL = IntExam[1].length;
  totalLength += IntExL;
} while (IntExam);
alert(totalLength);

或简洁版(源自JaromandaX的评论):

var Msg1 = "The lengh of <this> has to be calculated. And also <of this>. And of <this>";
var regex = /<([^>]*)>/g;
var totalLength = Msg1.match(regex).map(v => v.length-2).reduce((a, b) => a + b);
alert(totalLength);