在第n个字符后使用javascript或jquery插入换行符

时间:2012-03-08 21:13:36

标签: jquery split substring substr

http://worldalliancemaster/sites/dev/hospitals/hammond/services/cancer/stfranciscancer/Pages/What的-New.aspx

我想像第80个字符一样打破这个网址,剩下的就在下一行了。 有人可以用jquery来帮助我吗?

$(".srch-URL2").each(function() { 
    var html = $(this).html().substring(0,80);
    html = html[0] + "<br>" + html.slice(1).join(" "); 
    $(this).html(html); 
}); 

2 个答案:

答案 0 :(得分:3)

var left = myString.substring(0, 80);
var right = myString.substring(80);
var result = left + '<br />' + right;

http://jsfiddle.net/uYTPQ/

答案 1 :(得分:0)

ThiefMaster是正确的,因为你不需要jQuery来执行此操作:

var theURL = "http://worldalliancemaster/sites/dev/hospitals/hammond/services/cancer/stfranciscancer/Pages/What's-New.aspx";
var pieceOne = theURL.substr(0,80);
var pieceTwo = theURL.substr(80, theURL.length);

// Use jQuery for dom manipulation if you want
$('body').html(pieceOne + '<br />' + pieceTwo);

此外,如果你有一个非常长的字符串,并希望在每80个字符处打破它,你可以做这样的事情:

var theURL = "http://worldalliancemaster/sites/dev/hospitals/hammond/services/cancer/stfranciscancer/Pages/aster/sites/dev/hospitals/hammond/services/cancer/stfranciscancaster/sites/dev/hospitals/hammond/services/cancer/stfranciscancaster/sites/dev/hospitals/hammond/services/cancer/stfranciscancWhat's-New.aspx";

var breakAndInsertURL = function (url) {
    var urlToInsert = '';
    if (url.length <= 80) {
        urlToInsert = url;
    } else {
        for (var i = 0; i < url.length - 80; i += 80) {
            var newPiece = '';
            if (i != 0) {
                newPiece += '<br />';
            }
            newPiece += url.substr(i, i + 80);
            urlToInsert += newPiece;
        }
    }
    $('body').html(urlToInsert);
};

breakAndInsertURL(theURL);