gpt4 book ai didi

javascript - 如何解析字符串是否有换行

转载 作者:行者123 更新时间:2023-12-02 19:50:49 25 4
gpt4 key购买 nike

我想要一个带有 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."

关于javascript - 如何解析字符串是否有换行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9324373/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com