首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何解析字符串以进行换行

如何解析字符串以进行换行
EN

Stack Overflow用户
提问于 2012-02-17 15:21:11
回答 3查看 275关注 0票数 0

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

并根据所述参数对句子进行变换。

示例

代码语言:javascript
复制
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.

附言:

这是我尝试过的:

代码语言:javascript
复制
 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;
}

它是这样工作的:

代码语言:javascript
复制
 breakSentence()  // "javascript<br> is a lang<br>uage<br>"

 it should be:

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

回答 3

Stack Overflow用户

回答已采纳

发布于 2012-02-17 15:33:37

这里有一个解决方案:http://snippets.dzone.com/posts/show/869

代码语言:javascript
复制
//+ 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");
};

用法:

代码语言:javascript
复制
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."
票数 1
EN

Stack Overflow用户

发布于 2012-02-17 15:33:11

我会像这样试一试(未测试):

代码语言:javascript
复制
var breakSentence = function (sentence, maxCharLen, separator)
{
    var result = "";
    var index = 0;
    while (sentence.length - index > maxCharLen)
    {
        var spaceIndex = sentence.substring(index, index + maxCharLen).lastIndexOf(' ');
        if (spaceIndex < 0)    //no spaces
        {
            alert('Don\'t know what do do with substring with one long word');
            spaceIndex = maxCharLen;    //assume you want to break anyway to avoid infinite loop
        }
        result += sentence.substring(index, index + spaceIndex + 1)  + separator;
        index += spaceIndex + 1;
    }
    return result;
}

现在应该只在空格后中断...

票数 1
EN

Stack Overflow用户

发布于 2012-02-17 17:05:08

这是我尝试获得它的方法。它有两件事你应该注意:

  • 它首先删除所有分隔符实例(因此重新排序是完全新的)
  • 它不会将单词拆分超过maxCharLen字符。

它在节点0.6.10中工作

代码语言:javascript
复制
var breakSentence = function (sentence, maxCharLen, separator) {
  var words = []   // array of words
    , i            // iterator
    , len          // loop
    , current = '' // current line
    , lines = []    // lines split
    ;
  sentence = sentence || "javascript is a language";
  maxCharLen = 10 || maxCharLen;
  separator = separator || "<br>";
  sentence = sentence.replace(separator, '');
  if (sentence.length < maxCharLen) return [sentence]; // no need to work if we're already within limits
  words = sentence.split(' ');
  for (i = 0, len = words.length; i < len; i += 1) {
    // lets see how we add the next word. if the current line is blank, just add it and move on.
    if (current == '') {
      current += words[i];
    // if it's not like that, we need to see if the next word fits the current line
    } else if (current.length + words[i].length <= maxCharLen) { // if the equal part takes the space into consideration
      current += ' ' + words[i];
    // if the next word doesn't fit, start on the next line.
    } else {
      lines.push(current);
      current = words[i];
      // have to check if this is the last word
      if (i === len -1) {
        lines.push(current);
      }
    }
  }
  // now assemble the result and return it.
  sentence = '';
  for (i = 0, len = lines.length; i < len; i += 1) {
    sentence += lines[i];
    // add separator if not the last line
    if (i < len -1) {
      sentence += separator;
    }
  }
  return sentence;
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/9324373

复制
相关文章

相似问题

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