繁体   English   中英

在javascript中将字符串拆分为多行

[英]Splitting a string into multiple lines in javascript

我正在尝试找到一种将长字符串分割成多行的方法,所以我正在做的是将文本插入图像,如果时间太长则会溢出,换行就可以了,但是让用户添加不是最好的主意换行并在代码中拆分它,所以如果我给它一个限制,它会检查其超限是否拆分为两行,或者我的意思是换行符之间是\\ n,但是这很简单,但是我的问题是第二部分是如果超出限制,则应将其分成3个换行符,您将如何实现呢?

例子

split("sometext", 5); // somet\next
split("Hello", 2); // he\nll\no

https://j11y.io/snippets/wordwrap-for-javascript/

使用指定的字符数限制进行换行。 :)

您问题的答案很简单:

function customSplit(str, maxLength){
    if(str.length <= maxLength)
        return str;
    var reg = new RegExp(".{1," + maxLength + "}","g");
    var parts = str.match(reg);
    return parts.join('\n');
}

您要建立什么样的界面? 如果是Web界面,则应在前端设置字符串样式,而不要在数据层上对其进行修改。

如果这是一个基于文本的界面,而您确实需要执行此操作,那么当有一个非空字符串时,您可以获取前n字符,然后使用'\\ n'进行连接。 假设您有下划线:

function split(str, n) {
  let numberOfSegments = Math.ceil(_.size(str) / n);
  let segments = _.map(_.range(numberOfSegments), 
                       segmentIndex => str.substr(segmentIndex * n, n));
  return segments.join('\n');
}

您需要如下功能:

 function split(str, maxWidth) { const newLineStr = "\\n"; done = false; res = ''; do { found = false; // Inserts new line at first whitespace of the line for (i = maxWidth - 1; i >= 0; i--) { if (testWhite(str.charAt(i))) { res = res + [str.slice(0, i), newLineStr].join(''); str = str.slice(i + 1); found = true; break; } } // Inserts new line at maxWidth position, the word is too long to wrap if (!found) { res += [str.slice(0, maxWidth), newLineStr].join(''); str = str.slice(maxWidth); } if (str.length < maxWidth) done = true; } while (!done); return res + str; } function testWhite(x) { const white = new RegExp(/^\\s$/); return white.test(x.charAt(0)); }; console.log(split("sometext", 5)); console.log(split("Hello", 2)); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM