Thursday, January 19, 2017

Javascript shorten string without cutting words (Or) Javascript trim multiline string without cutting words

In this article i will give Javascript code for trim multiline string without cutting words.
Here i am giving an example,

say i had the string text = "this is a long string i cant display" i want to trim it down to 10 characters but if it does't end with a space finish the word i don't want the string variable to look like this "this is a long string i cant dis" i want it to finish the word until a space occurs.

So here is the solution. You can directly copy and paste the code and run your code.

Solution One:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
   // SHORTEN STRING TO WHOLE WORDS
function shorten(s,l) {
  return (s.match(new RegExp(".{"+l+"}\\S*"))||[s])[0];
}
alert( shorten("The quick brown fox jumps over the lazy dog", 5) );
});
</script>
</head>
<body>
</body>
</html>

Solution Two:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
infotext="this is a longish string of test.\n bla bla bla bla text here";
infotext = infotext.match(/^.*$/m)[0].replace(/^([\s\S]{10}\S*).*/, "$1");
alert(infotext);
</script>
</head>
<body>
</body>
</html>

Hope this article is useful for you. If you like please share. If still you have any queries please comment below.
Thankyou

1 comment:

  1. thanks for this little script! for easy string truncations i also like to use the cuttr.js library (JS and jQuery) for - js three dots solution - its possible to cut characters, words or even sentences :)

    ReplyDelete

Popular Posts