我想要一个带有3个参数的函数:
句子(字符串),
maxCharLen = 20(数字),
分隔符(字符串)

然后根据参数对句子进行变换



var sentence = "JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions."

var newSentence = breakSentence(sentence, maxCharLen=20, separator="<br>");

newSentence // JavaScript is a prototype-based  <br> scripting language that is dynamic, <br> weakly typed and has first-class functions.


附言:

这是我尝试过的:

 var breakSentence = function (sentence, maxCharLen, separator)
 {
   sentence = sentence || "javascript is a language" ;
   maxCharLen = 10 || maxCharLen; // max numb of chars for line
   separator = "<br>" || separator;

   var offset;
   var nbBreak = sentence.length // maxCharLen;
   var newSentence = "";

   for (var c = 0; c < nbBreak; c += 1)
   {
    offset = c * maxCharLen;
    newSentence += sentence.substring(offset, offset + maxCharLen) + separator;
   }

   return newSentence;
}


它以这种方式工作:

 breakSentence()  // "javascript<br> is a lang<br>uage<br>"

 it should be:

 breakSentence()  // "javascript<br>is a <br>language"

最佳答案

解决方法:http://snippets.dzone.com/posts/show/869

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com/string/wordwrap [v1.0]

String.prototype.wordWrap = function(m, b, c){
    var i, j, l, s, r;
    if(m < 1)
        return this;
    for(i = -1, l = (r = this.split("\n")).length; ++i < l; r[i] += s)
        for(s = r[i], r[i] = ""; s.length > m; r[i] += s.slice(0, j) + ((s = s.slice(j)).length ? b : ""))
            j = c == 2 || (j = s.slice(0, m + 1).match(/\S*(\s)?$/))[1] ? m : j.input.length - j[0].length
            || c == 1 && m || j.input.length + (j = s.slice(m).match(/^\S*/)).input.length;
    return r.join("\n");
};


用法:

var sentence = "JavaScript is a prototype-based scripting language that is dynamic, weakly typed and has first-class functions."
sentence.wordWrap(20, "<br>",true)
// Output "JavaScript is a <br>prototype-based <br>scripting language <br>that is dynamic, <br>weakly typed and has<br> first-class <br>functions."

10-02 12:18
查看更多