Truncate a string straight JavaScript
JavascriptTruncateJavascript Problem Overview
I'd like to truncate a dynamically loaded string using straight JavaScript. It's a url, so there are no spaces, and I obviously don't care about word boundaries, just characters.
Here's what I got:
var pathname = document.referrer; //wont work if accessing file:// paths
document.getElementById("foo").innerHTML = "<a href='" + pathname +"'>" + pathname +"</a>"
Javascript Solutions
Solution 1 - Javascript
Use the substring method:
var length = 3;
var myString = "ABCDEFG";
var myTruncatedString = myString.substring(0,length);
// The value of myTruncatedString is "ABC"
So in your case:
var length = 3; // set to the number of characters you want to keep
var pathname = document.referrer;
var trimmedPathname = pathname.substring(0, Math.min(length,pathname.length));
document.getElementById("foo").innerHTML =
"<a href='" + pathname +"'>" + trimmedPathname + "</a>"
Solution 2 - Javascript
Here's one method you can use. This is the answer for one of FreeCodeCamp Challenges:
function truncateString(str, num) {
if (str.length > num) {
return str.slice(0, num) + "...";
} else {
return str;
}
}
Solution 3 - Javascript
yes, substring. You don't need to do a Math.min; substring with a longer index than the length of the string ends at the original length.
But!
document.getElementById("foo").innerHTML = "<a href='" + pathname +"'>" + pathname +"</a>"
This is a mistake. What if document.referrer had an apostrophe in? Or various other characters that have special meaning in HTML. In the worst case, attacker code in the referrer could inject JavaScript into your page, which is a XSS security hole.
Whilst it's possible to escape the characters in pathname manually to stop this happening, it's a bit of a pain. You're better off using DOM methods than fiddling with innerHTML strings.
if (document.referrer) {
var trimmed= document.referrer.substring(0, 64);
var link= document.createElement('a');
link.href= document.referrer;
link.appendChild(document.createTextNode(trimmed));
document.getElementById('foo').appendChild(link);
}
Solution 4 - Javascript
Following code truncates a string and will not split words up, and instead discard the word where the truncation occurred. Totally based on Sugar.js source.
function truncateOnWord(str, limit) {
var trimmable = '\u0009\u000A\u000B\u000C\u000D\u0020\u00A0\u1680\u180E\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200A\u202F\u205F\u2028\u2029\u3000\uFEFF';
var reg = new RegExp('(?=[' + trimmable + '])');
var words = str.split(reg);
var count = 0;
return words.filter(function(word) {
count += word.length;
return count <= limit;
}).join('');
}
Solution 5 - Javascript
Updated ES6 version
const truncateString = (string = '', maxLength = 50) =>
string.length > maxLength
? `${string.substring(0, maxLength)}…`
: string
// demo the above function
console.log(
truncateString(prompt("", "This is a test"), 4)
)
Solution 6 - Javascript
Thought I would give Sugar.js a mention. It has a truncate method that is pretty smart.
From the documentation:
>
Truncates a string. Unless class="optional parameter">split is true, class="code">truncate will not split words up, and instead > discard the word where the truncation occurred.
Example:
'just sittin on the dock of the bay'.truncate(20)
Output:
just sitting on...
Solution 7 - Javascript
Yes, substring
works great:
stringTruncate('Hello world', 5); //output "Hello..."
stringTruncate('Hello world', 20);//output "Hello world"
var stringTruncate = function(str, length){
var dots = str.length > length ? '...' : '';
return str.substring(0, length)+dots;
};
Solution 8 - Javascript
Besides the substring method, i found a nice little JS lib for this purpose.
It has mutliple useful methods in vanilla javascript to truncate a string.
Truncation by characters:
var pathname = 'this/is/thepathname';
document.getElementById("foo").innerHTML = "<a class='link' href='" + pathname +"'>" + pathname +"</a>"
// call the plugin - character truncation only needs a one line init
new Cuttr('.link', { length: 10 });
<script src="https://cdnjs.cloudflare.com/ajax/libs/cuttr/1.3.2/cuttr.min.js"></script>
<div id="foo"></div>
Simply add a class
to the a
and init the plugin.
Multiline text clipping is also possible.
More options like word oder sentences truncation are mentioned in the cuttr.js docs on the github page.
Solution 9 - Javascript
in case you want to truncate by word.
function limit(str, limit, end) {
limit = (limit)? limit : 100;
end = (end)? end : '...';
str = str.split(' ');
if (str.length > limit) {
var cutTolimit = str.slice(0, limit);
return cutTolimit.join(' ') + ' ' + end;
}
return str.join(' ');
}
var limit = limit('ILorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus metus magna, maximus a dictum et, hendrerit ac ligula. Vestibulum massa sapien, venenatis et massa vel, commodo elementum turpis. Nullam cursus, enim in semper luctus, odio turpis dictum lectus', 20);
console.log(limit);
Solution 10 - Javascript
You can fix this method with the help of internal JavaScript methods
const truncate = (text, len) => {
if (text.length > len && text.length > 0) {
return `${text.split(" ").slice(0, len).join(" ")} ...`;
} else {
return text;
}
};
Solution 11 - Javascript
var pa = document.getElementsByTagName('p')[0].innerHTML;
var rpa = document.getElementsByTagName('p')[0];
// console.log(pa.slice(0, 30));
var newPa = pa.slice(0, 29).concat('...');
rpa.textContent = newPa;
console.log(newPa)
<p>
some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here some text here
</p>
Solution 12 - Javascript
var str = "Anything you type in.";
str.substring(0, 5) + "" //you can type any amount of length you want
Solution 13 - Javascript
In case you want to truncate by Limit (symbols), but you don't want to cut the words (leave the last word intact) for not LONG text (head of post for example):
trancWord(str, limit) {
str = str.split(' ');
let summ = 0
for (let [index, value] of str.entries()) {
summ += value.length
if (summ > limit) {
let cutTolimit = str.slice(0, index);
return str.slice(0, index).join(' ') + ' ' + '...';
}
}
return str.join(' ');
}
For long String (some long Text of Post - Vue-3 use as Filter):
trancWord (str, max){
if (str.length <= max) { return str; }
let subString = str.substr(0, max);
return (str ? subString.substr(0, subString.lastIndexOf(' ')) : subString) + '...';
}