是否有任何Javascript库可以智能地截断字符串?

时间:2012-11-15 10:58:07

标签: javascript

我需要截断侧边菜单中的字符串,使它们适合没有换行符的div。 div具有固定的宽度。我正在找一个图书馆为我做这件事。 如果一个字符串太长而不适合div,它应该被截断为:

<div>This string is too long</div> ==&gt; <div>This string is...ong</div>

正如您所看到的,字符串不仅被省略号截断,而且最后三个字母也是可见的。这是为了提高可读性。截断不应该关心空格。

有谁知道包含此类功能的库?我们主要在整个项目中使用jQuery。

提前致谢!

3 个答案:

答案 0 :(得分:2)

我不知道库本身就是这样,但是使用HTML5 Canvas和Canvas text metrics,你可以确定字符串是否适合,如果没有,你需要多少钱把它剪掉了。

var canvas = document.createElement('canvas');
var context = canvas.getContext('2d');
context.font = '12pt Arial';
var metrics = context.measureText('measure me!');
var width=metrics.width;

答案 1 :(得分:2)

我使用jQuery.dotdotdot后。

将您的HTML视为

<div class="longtext">This string is too long</div>

使用dotdotdot

后使用此javascript
$(document).ready(function() {
    $(".longtext").dotdotdot();
});

访问他们的网站以获取更多可配置选项。

答案 2 :(得分:1)

This JSFiddle显示了一个简单的解决方案:

/**
 * Uses canvas.measureText to compute and return the width of the given text of given font.
 * 
 * @param text The text to be rendered.
 * @param {String=} fontStyle The style of the font (e.g. "bold 12pt verdana").
 * @param {Element=} canvas An optional canvas element to improve performance. If not given, the function will create a new temporary canvas element.
 * 
 * @see http://stackoverflow.com/questions/118241/calculate-text-width-with-javascript/21015393#21015393
 */
function getTextWidth(text, fontStyle, canvas) {
    // if given, use cached canvas for better performance
    // else, create new canvas
    canvas = canvas || document.createElement("canvas");
    var context = canvas.getContext("2d");
    context.font = fontStyle;
    var metrics = context.measureText(text);
    return metrics.width;
}


/**
 * Returns text whose display width does not exceed the given maxWidth.
 * If the given text is too wide, it will be truncated so that text + ellipsis
 * is still less than maxWidth wide.
 * 
 * @param text The text to be truncated.
 * @param {String} fontStyle The font style that the string is to be rendered with.
 * @param maxWidth Max display width of string.
 * @param {String=} ellipsis Set to "..." by default.
 * @param {Element=} canvas Optional canvas object to improve performance.
 * 
 */
function truncateText(text, fontStyle, maxWidth, ellipsis, canvas) {
    var width;
    var len = text.length;
    ellipsis = ellipsis || "...";
    while ((width = getTextWidth(text, fontStyle, canvas)) > maxWidth) {
        --len;
        text = text.substring(0, len) + ellipsis;
    }
    return text;
}

示例:

var maxWidth = 200;
var fontStyle = "bold 12pt arial";
var text = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.";
var truncatedText = truncateText(text, fontStyle, maxWidth)
console.log(truncatedText);

生成:“Lorem ipsum dolor坐......”