使用Javascript

时间:2017-04-03 07:01:20

标签: javascript line break

我尝试使用以下代码行来检查字符串是否大于46个字符。如果它更长,它会每46个字符打破一个新行,但是,我没有这样做。

谁能告诉我什么是错的?



function ContentFormat(content)
{
    var start = "";
    var end = "";
    var space = "<br/>&nbsp; &nbsp;";
    var newcontent = "";
    var toadd = "";
    if (content.length > 46)
    {
        for (var i = 0, len = content.length; i < len; i++) {
            if(i/46 == 0)
            {
                start = content.slice(0, i);
                end = content.slice(i);
                toadd = start.concat(space, end);
            }
            newcontent = toadd;
            toadd = "";
        }
    }
    return newcontent;
}
&#13;
&#13;
&#13;

3 个答案:

答案 0 :(得分:0)

你在for循环&amp;中做错了如果条件。

function ContentFormat(content)
{
    var start = "";
    var end = "";
    var space = "<br/>&nbsp; &nbsp;";
    var newcontent = "";
    var toadd = "";
    var len = content.length
    if (len > 46)
    {
        for (var i = 0; i < len; i++) {
            if(i%46 == 0)
            {
                start = content.slice(0, i);
                end = content.slice(i);
                toadd = start.concat(space, end);
            }
            newcontent = toadd;
        }
    }
}

答案 1 :(得分:0)

您的逻辑完全错误,使用下面的代码而不是您的代码来添加46个字符后的中断!

function ContentFormat(content)
{
    var leftPortion = "";
    var space = "<br/>&nbsp; &nbsp;";
    var newcontent = "";
    while (content.length > 46)
    {
        leftPortion = content.slice(0, 45);
        content = content.slice(45);
        newcontent = newcontent + leftPortion + space;
    }
    newcontent = newcontent + content;
    window.alert(newcontent);
}

答案 2 :(得分:0)

使用正则表达式和String.replace方法也可以实现这一点。

var str = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';

function breakEvery(str, interval, breaker) {
    if (str === void 0) { str = ""; }
    if (interval === void 0) { interval = 0; }
    if (breaker === void 0) { breaker = "\n"; }
    if (str.length < interval) {
        return str;
    }
    var re = new RegExp('.{' + interval + '}', "ig");
    return str.replace(re, function (part) { return part + breaker; });
}

console.log(breakEvery(str, 46, "\n<br/>&nbsp; &nbsp;"));