Trim text to the nearest space... ('-' * 33) Demos a custom function called trimText(), which trims text to the nearest space just before the 50 character length and so avoiding odd characters just before the...
A Pen by Siôn J. Lewis on CodePen.
<div id="container"></div> |
namespace = function (ns_string, obj) { | |
var parts = ns_string.split('.'), | |
parent = window, | |
pl, i; | |
for (i = 0, pl = parts.length; i < pl; i++) { | |
parent = parent[parts[i]] = parent[parts[i]] || (i == pl - 1 && obj ? (typeof obj == 'function' ? (obj() || {}) : obj) : {}); | |
} | |
return parent; | |
}; | |
namespace("SJL.Util", function () { | |
var self = {}; | |
self.trimText = function (text, len) { | |
// Take into account the '...'. | |
len = len - 3; | |
if (text != undefined && text.length > len) { | |
var tmp = jQuery.trim(text).substring(0, len).split(" ") | |
var text = tmp.slice(0, tmp.length - 1).join(" ") + "..."; | |
// And replace any rogue commas. | |
text = text.replace(',...', '...'); | |
} | |
return text; | |
} | |
return self; | |
}); | |
$(function () { | |
var txtBefore = 'This is a test description used to show the trimText function.'; | |
var txtAfter = SJL.Util.trimText(txtBefore, 50); | |
$('#container').html(txtAfter); | |
}); |
Trim text to the nearest space... ('-' * 33) Demos a custom function called trimText(), which trims text to the nearest space just before the 50 character length and so avoiding odd characters just before the...
A Pen by Siôn J. Lewis on CodePen.