Reputation: 3719
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>
Upvotes: 0
Views: 70
Reputation: 191
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>
Upvotes: 4