如何使用变量在Javascript中构造正则表达式字符串

时间:2017-03-30 20:02:37

标签: javascript jquery regex

我发现了类似的问题,由于这些问题,我认为我已经接近了,但这仍然没有做我想要的。 (JQuery已经在这个项目中使用,所以我也在使用它。)

保存的代码段有效。如果我注释掉当前的替换行并取消评论当前评论的那一行,它似乎什么都不做。它应该找到文本中的第一个maxWordschars字符,以及直到下一个空格的任何字符,并将字符串替换为已找到的字符。

  $('.practice').each(function(){
      var maxWordschars = 34;
      var strippedString = $(this).text().trim();        
      var regexpattern = new RegExp("/^(.{" + maxWordschars + "}[^\s]*).*/");
      var newString = strippedString.replace(/^(.{34}[^\s]*).*/, "$1");
      //var newString = strippedString.replace(regexpattern, "$1");
      if (newString != strippedString){
        newString += "...";
      }      
      $(this).text(newString);
  });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="practice">
  Let this be a long string of text that my script has to deal with to make it fit.
</div>
<br>
<div class="practice">
  Allow this considerably longer paragraph of text with multisylable enunciations to further quantify the effectiveness of my script
</div>

1 个答案:

答案 0 :(得分:4)

  $('.practice').each(function(){
      var maxWordschars = 34;
      var strippedString = $(this).text().trim();        
      var regexpattern = new RegExp("^(.{" + maxWordschars + "}\\S*).*");
      //var newString = strippedString.replace(/^(.{34}[^\s]*).*/, "$1");
      var newString = strippedString.replace(regexpattern, "$1");
      if (newString != strippedString){
        newString += "...";
      }      
      $(this).text(newString);
  });

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="practice">
  Let this be a long string of text that my script has to deal with to make it fit.
</div>
<br>
<div class="practice">
  Allow this considerably longer paragraph of text with multisylable enunciations to further quantify the effectiveness of my script
</div>
{{1}}