If the length of the string is less than or equal to the given number, just return the string without truncating it. Otherwise, truncate the string. Meaning keep the beginning of the string up until the given number and discard the rest. Add “…” to the end of the truncated string and return it.
String strip() in JavaScript We can strip a string using trim() method and can remove unnecessary trailing and leading spaces and tabs from the string. Example: HTML.
If I understand correctly, you want to shorten a string to a certain length (e.g. shorten "The quick brown fox jumps over the lazy dog"
to, say, 6 characters without cutting off any word).
If this is the case, you can try something like the following:
var yourString = "The quick brown fox jumps over the lazy dog"; //replace with your string.
var maxLength = 6 // maximum number of characters to extract
//trim the string to the maximum length
var trimmedString = yourString.substr(0, maxLength);
//re-trim if we are in the middle of a word
trimmedString = trimmedString.substr(0, Math.min(trimmedString.length, trimmedString.lastIndexOf(" ")))
There are lots of ways to do it, but a regular expression is a useful one line method:
"this is a longish string of text".replace(/^(.{11}[^\s]*).*/, "$1");
//"this is a longish"
This expressions returns the first 11 (any) characters plus any subsequent non-space characters.
Example script:
<pre>
<script>
var t = "this is a longish string of text";
document.write("1: " + t.replace(/^(.{1}[^\s]*).*/, "$1") + "\n");
document.write("2: " + t.replace(/^(.{2}[^\s]*).*/, "$1") + "\n");
document.write("5: " + t.replace(/^(.{5}[^\s]*).*/, "$1") + "\n");
document.write("11: " + t.replace(/^(.{11}[^\s]*).*/, "$1") + "\n");
document.write("20: " + t.replace(/^(.{20}[^\s]*).*/, "$1") + "\n");
document.write("100: " + t.replace(/^(.{100}[^\s]*).*/, "$1") + "\n");
</script>
Output:
1: this
2: this
5: this is
11: this is a longish
20: this is a longish string
100: this is a longish string of text
I am kind of surprised that for a simple problem like this there are so many answers that are difficult to read and some, including the chosen one, do not work .
I usually want the result string to be at most maxLen
characters.
I also use this same function to shorten the slugs in URLs.
str.lastIndexOf(searchValue[, fromIndex])
takes a second parameter that is the index at which to start searching backwards in the string making things efficient and simple.
// Shorten a string to less than maxLen characters without truncating words.
function shorten(str, maxLen, separator = ' ') {
if (str.length <= maxLen) return str;
return str.substr(0, str.lastIndexOf(separator, maxLen));
}
This is a sample output:
for (var i = 0; i < 50; i += 3)
console.log(i, shorten("The quick brown fox jumps over the lazy dog", i));
0 ""
3 "The"
6 "The"
9 "The quick"
12 "The quick"
15 "The quick brown"
18 "The quick brown"
21 "The quick brown fox"
24 "The quick brown fox"
27 "The quick brown fox jumps"
30 "The quick brown fox jumps over"
33 "The quick brown fox jumps over"
36 "The quick brown fox jumps over the"
39 "The quick brown fox jumps over the lazy"
42 "The quick brown fox jumps over the lazy"
45 "The quick brown fox jumps over the lazy dog"
48 "The quick brown fox jumps over the lazy dog"
And for the slug:
for (var i = 0; i < 50; i += 10)
console.log(i, shorten("the-quick-brown-fox-jumps-over-the-lazy-dog", i, '-'));
0 ""
10 "the-quick"
20 "the-quick-brown-fox"
30 "the-quick-brown-fox-jumps-over"
40 "the-quick-brown-fox-jumps-over-the-lazy"
Everyone seems to forget that indexOf takes two arguments- the string to match, and the character index to start looking from. You can break the string at the first space after 10 characters.
function cutString(s, n){
var cut= s.indexOf(' ', n);
if(cut== -1) return s;
return s.substring(0, cut)
}
var s= "this is a long string i cant display";
cutString(s, 10)
/* returned value: (String)
this is a long
*/
Lodash has a function specifically written for this: _.truncate
const truncate = _.truncate
const str = 'The quick brown fox jumps over the lazy dog'
truncate(str, {
length: 30, // maximum 30 characters
separator: /,?\.* +/ // separate by spaces, including preceding commas and periods
})
// 'The quick brown fox jumps...'
Here is a solution in one line.
text = "this is a long string I cant display"
function shorten(text,max) {
return text && text.length > max ? text.slice(0,max).split(' ').slice(0, -1).join(' ') : text
}
console.log(shorten(text,10));
Based on NT3RP answer which does not handle some corner cases, I've made this code.
It guarantees to not return a text with a size > maxLength event an ellipsis ...
was added at the end.
This also handle some corner cases like a text which have a single word being > maxLength
shorten: function(text,maxLength,options) {
if ( text.length <= maxLength ) {
return text;
}
if ( !options ) options = {};
var defaultOptions = {
// By default we add an ellipsis at the end
suffix: true,
suffixString: " ...",
// By default we preserve word boundaries
preserveWordBoundaries: true,
wordSeparator: " "
};
$.extend(options, defaultOptions);
// Compute suffix to use (eventually add an ellipsis)
var suffix = "";
if ( text.length > maxLength && options.suffix) {
suffix = options.suffixString;
}
// Compute the index at which we have to cut the text
var maxTextLength = maxLength - suffix.length;
var cutIndex;
if ( options.preserveWordBoundaries ) {
// We use +1 because the extra char is either a space or will be cut anyway
// This permits to avoid removing an extra word when there's a space at the maxTextLength index
var lastWordSeparatorIndex = text.lastIndexOf(options.wordSeparator, maxTextLength+1);
// We include 0 because if have a "very long first word" (size > maxLength), we still don't want to cut it
// But just display "...". But in this case the user should probably use preserveWordBoundaries:false...
cutIndex = lastWordSeparatorIndex > 0 ? lastWordSeparatorIndex : maxTextLength;
} else {
cutIndex = maxTextLength;
}
var newText = text.substr(0,cutIndex);
return newText + suffix;
}
I guess you can easily remove the jquery dependency if this bothers you.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With