Breaking a line into different lines?

In javascript, how to split my line if it exceeds 25 characters into two lines, if my line contains 75 characters, I want the line to be in three lines of 25 characters.

early

+3
source share
4 answers

This is very easy to do with a regex:

var text = '75 characters long (really!) — well... maybe not, but you get the picture.',
    broken;
broken = text.replace(/([^\0]{25})/g, '$1\n');

As shown here: http://jsbin.com/ajiyo/3 .

Change . To explain the regex: it will match any character string (collection of every character except NUL) 25 characters long.

The brackets () mean that this part must be captured, and the "$ 1" part of the second argument (replacement string) refers to this first capture.

25 " ". 25 , , .

2nd edit: , , . , NUL, NUL .

+6

-

var point=0;

var myStr="12345678901234567890ABCDE my very long string 12345678901234567890ABCDE";
var myRes="";
while(myStr.substring(point).length>25)
{
  myRes=myRes+myStr.substring(point,point+25)+"\n"
  point+=25;
}

return myRes+myStr.substring(point);
+2

This should be pretty close:

var txt = "This is a really long string that should be broken up onto lines of 25 characters, or less.";

for (i=0;i<(Math.ceil(txt.length/25));i++) {
    document.write(txt.substring(25*i,25*(i+1)) + "<br />");
}

See working example:

http://jsfiddle.net/dbgDj/

+1
source

Use str_split (php) equivalent in javascript

http://phpjs.org/functions/str_split∗30

 function str_split (string, split_length) {
    // Convert a string to an array. If split_length is specified,
    // break the string down into chunks each split_length characters long.  
    // 
    // version: 1101.3117
    // discuss at: http://phpjs.org/functions/str_split    
    // +     original by: Martijn Wieringa
    // +     improved by: Brett Zamir (http://brett-zamir.me)
    // +     bugfixed by: Onno Marsman
    // +      revised by: Theriault
    // +        input by: Bjorn Roesbeke (http://www.bjornroesbeke.be/)    
    // +      revised by: Rafał Kukawski (http://blog.kukawski.pl/)
    // *       example 1: str_split('Hello Friend', 3);
    // *       returns 1: ['Hel', 'lo ', 'Fri', 'end']

    if (split_length === null) {
        split_length = 1;    }
    if (string === null || split_length < 1) {
        return false;
    }
    string += '';
    var chunks = [], pos = 0, len = string.length;
    while (pos < len) {
        chunks.push(string.slice(pos, pos += split_length));
    }
    return chunks;
}
0
source

Source: https://habr.com/ru/post/1789417/


All Articles