0

I've found similar questions and, thanks to those question, I think I've come close, but this still isn't doing what I want. (JQuery is already in use on this project, so I'm using it too.)

The snippet, as saved, works. If I comment out the current replace line and un-comment the one that's currently a comment, It seems to do nothing. It's supposed to find the first maxWordschars characters from the text, and any characters up to the next space and replace the string with what has been found.

  $('.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>

6

1 Answer 1

4
var regexpattern = new RegExp("^(.{" + maxWordschars + "}\\S*).*");

  $('.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>

Sign up to request clarification or add additional context in comments.

2 Comments

I found that \\w* works as well as \\S* and syntactically is what I really want to do. (Match word characters instead of matching non-space characters.)
\w === [a-zA-Z0-9_] 'my $a here'.replace(/^(.{3}\w*).*/, '$1...') // my ... 'my $a here'.replace(/^(.{3}\S*).*/, '$1...') // my $a...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.