Skip to content

Instantly share code, notes, and snippets.

@sionjlewis
Last active August 29, 2015 14:22
Show Gist options
  • Save sionjlewis/7a2fe1a6dfd49c36410b to your computer and use it in GitHub Desktop.
Save sionjlewis/7a2fe1a6dfd49c36410b to your computer and use it in GitHub Desktop.
Trim text to the nearest space...
<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.

License.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment