首页 > 解决方案 > 在第 n 次出现换行符后剪切字符串(性能)

问题描述

我目前正在尝试找到一种在 div 内分割换行符的有效方法。我可以使用任何人推荐的任何东西,只要它高效并且不需要任何 JavaScript 框架,只需要 JQuery。

我制作了以下工作原型,但我不知道与其他方法相比它的效率如何。 JSFiddle

(function($) {
  $(document).ready(function(){
    $('#Lines').on('change', function(){
      $('#Entry').change()
    });
    
    $('#Entry').on('change', function(){
      var _a = $(this).val(),
      _d = '\n',
      _s = $('#Lines').val(),
      _t = _a.split(_d).slice(0, _s),
      _r = _t.join(_d);

      $('#Original > div.Data').text(_a);
      $('#Modified > div.Data').text(_r);
    });
    
    $('#Entry').val('1 Line\n2 Line\n3 Line\n4 Line\n5 Line\n6 Line\n7 Line\n8 Line\n9 Line\n10 Line').change();
  });
})(jQuery);
body {
  font-family: Roboto;
}

.Data {
  white-space: pre-wrap;
}

.Title {
  font-size: 20px;
  font-weight: 600;
}

.input {
  display: inline-block;
  float: right;
}

#Original,
#Modified,
#Entry,
.input{
  -webkit-box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14),
    0 3px 1px -2px rgba(0, 0, 0, 0.12), 0 1px 5px 0 rgba(0, 0, 0, 0.2);
  box-shadow: 0 2px 2px 0 rgba(0, 0, 0, 0.14),
    0 3px 1px -2px rgba(0, 0, 0, 0.12), 0 1px 5px 0 rgba(0, 0, 0, 0.2);
  padding: 10px;
}

.border-box {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
}

.w-100 {
  width: 100%;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
  <div class='input'>
    NUMBER OF NEW LINES TO SLICE:
  <input type="number" name="Lines" id="Lines" value='2'>
  </div>
  <div class='w-100'>
    <textarea id="Entry" class="w-100 border-box" rows="10"></textarea>
  </div>
</div>
<br/>

<div id='Modified'>
  <div class='Title'>Modified</div>
  <br/>
  <div class='Data'></div>
</div>

<br/>

<div id='Original'>
  <div class='Title'>Original</div>
  </br>
  <div class='Data'></div>
</div>

标签: javascriptjqueryhtmlcssperformance

解决方案


我认为最快的代码是避免额外的操作,如字符串拆分/连接或正则表达式。您可以使用 indexOf 找到 \n,获取您感兴趣的最后一个 \n 的索引并执行单个 .slice() 调用。如果您发现所需的 \n 字符较少,则只需返回完整字符串。

function splitLine(str, countLines) {
    if (!str) {
        return str; 
    }
    if (countLines <= 0) {
        return '';
    }
    let nlIndex = -1;
    let newLinesFound = 0;
    while(newLinesFound < countLines) {
        let nextIndex = str.indexOf('\n', nlIndex + 1);
        if (nextIndex === -1) {
            return str;
        }
        nlIndex = nextIndex;
        newLinesFound++;
    }
    return str.slice(0, nlIndex);
}

推荐阅读