首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >在JavaScript中自动换行文本

在JavaScript中自动换行文本
EN

Stack Overflow用户
提问于 2013-01-24 00:41:28
回答 11查看 84.1K关注 0票数 29

我是JavaScript和jQuery的新手。

我在JavaScript中有一个名为str的变量,它包含非常长的文本,如下所示

代码语言:javascript
复制
"A quick brown fox jumps over a lazy dog". 

我想包装它,并通过在正确的位置插入适当的strbr/标记将其赋给相同的变量\n

我不想使用CSS等,你能告诉我如何在JavaScript中使用适当的函数来获取str并向其返回适当的格式化文本吗?

类似于:

代码语言:javascript
复制
str = somefunction(str, maxchar);

我试了很多,但不幸的是没有我想要的那样!

任何帮助都将不胜感激。

EN

回答 11

Stack Overflow用户

回答已采纳

发布于 2013-01-24 03:05:27

这应该在最近的空格maxChar处插入一个换行符:

代码语言:javascript
复制
str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It w as popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

str = wordWrap(str, 40);

function wordWrap(str, maxWidth) {
    var newLineStr = "\n"; done = false; res = '';
    while (str.length > maxWidth) {                 
        found = false;
        // Inserts new line at first whitespace of the line
        for (i = maxWidth - 1; i >= 0; i--) {
            if (testWhite(str.charAt(i))) {
                res = res + [str.slice(0, i), newLineStr].join('');
                str = str.slice(i + 1);
                found = true;
                break;
            }
        }
        // Inserts new line at maxWidth position, the word is too long to wrap
        if (!found) {
            res += [str.slice(0, maxWidth), newLineStr].join('');
            str = str.slice(maxWidth);
        }

    }

    return res + str;
}

function testWhite(x) {
    var white = new RegExp(/^\s$/);
    return white.test(x.charAt(0));
};
票数 30
EN

Stack Overflow用户

发布于 2016-08-02 07:42:22

我的版本。它返回一个行数组而不是字符串,因为它可以更灵活地选择要使用的行分隔符(如newline或html BR)。

代码语言:javascript
复制
function wordWrapToStringList (text, maxLength) {
    var result = [], line = [];
    var length = 0;
    text.split(" ").forEach(function(word) {
        if ((length + word.length) >= maxLength) {
            result.push(line.join(" "));
            line = []; length = 0;
        }
        length += word.length + 1;
        line.push(word);
    });
    if (line.length > 0) {
        result.push(line.join(" "));
    }
    return result;
};

要将线性数组从字符串转换为字符串,请执行以下操作:

代码语言:javascript
复制
wordWrapToStringList(textToWrap, 80).join('<br/>');

请注意,它只做单词换行,不会打断长单词,而且它可能不是最快的。

票数 8
EN

Stack Overflow用户

发布于 2015-11-26 22:45:49

许多这样的行为可以通过使用正则表达式(使用具有最少匹配字符数的非贪婪量词或具有最大字符数的贪婪量词,取决于您需要的行为)作为单行程序来实现。

下面显示了一个非贪婪的全局替换,它在节点V8 REPL中工作,因此您可以看到命令和结果。然而,同样的方法也应该在浏览器中工作。

此模式搜索与定义的组匹配的至少10个字符( \w表示单词字符,\s表示空格字符),并将模式锚定在\b单词边界上。然后,它使用反向引用将原始匹配项替换为附加了换行符的匹配项(在本例中,可以选择替换括号后的反向引用中未捕获的空格字符)。

代码语言:javascript
复制
> s = "This is a paragraph with several words in it."
'This is a paragraph with several words in it.'
> s.replace(/([\w\s]{10,}?)\s?\b/g, "$1\n")
'This is a \nparagraph \nwith several\nwords in it\n.'

在原始海报要求的格式中,这可能看起来像...

代码语言:javascript
复制
var str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It w as popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

function wordWrap(text,width){
    var re = new RegExp("([\\w\\s]{" + (width - 2) + ",}?\\w)\\s?\\b", "g")
    return text.replace(re,"$1\n")
}

> wordWrap(str,40)
'Lorem Ipsum is simply dummy text of the\nprinting and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s\n, when an unknown printer took a galley of\ntype and scrambled it to make a type specimen\nbook. It has survived not only five centuries\n, but also the leap into electronic typesetting\n, remaining essentially unchanged. It w as popularised in the 1960s with the\nrelease of Letraset sheets containing Lorem\nIpsum passages, and more recently with desktop publishing\nsoftware like Aldus PageMaker including\nversions of Lorem Ipsum.'
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14484787

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档