Insert line break in CSV to each N characters

1

I have a js code that has a var that receives a string and this string needs to be broken every n lines so as not to break the maximum width of the csv content. Also, it is necessary that no word is broken in half.

What would be the best solution for this? Considering the following example:

var n = 50;
var str = "Testando um algoritmo para quebrar esse texto a cada n caracteres sem haver quebra de palavras";
    
asked by anonymous 03.02.2015 / 00:19

2 answers

0

Hello friend searching the internet I found this function:

function wordwrap( str, width, brk, cut ) {

    brk = brk || '\n';
    width = width || 75;
    cut = cut || false;

    if (!str) { return str; }

    var regex = '.{1,' +width+ '}(\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\S+?(\s|$)');

     return str.match( RegExp(regex, 'g') ).join( brk );
}

Usage:

wordwrap('The quick brown fox jumped over the lazy dog.', 20, '<br/>\n');

Result:
The quick brown fox
jumped over the lazy
dog.

Function with concatenation of start and end:

  function wordwrap( str, width, brk) {

    brk = brk || '\n';
    width = width || 75;

    if (!str) { return str; }

    var regex = '.{1,' +width+ '}(\s|$)' + '|\S+?(\s|$)';

    var array = str.match( RegExp(regex, 'g') );

    var frase = "";

    for (var i = 0; i < array.length; i++) {
        console.log(array[i]);

        frase += i + " " + array[i] + "\n";
    };

    return frase;
   }

alert(wordwrap('The quick brown fox jumped over the lazy dog.', 30));
    
03.02.2015 / 00:51
0

You can use the following function that reproduces PHP's wordwrap operation.

function wordwrap( str, width, brk, cut ) {

    brk = brk || '\n';
    width = width || 75;
    cut = cut || false;

    if (!str) { return str; }

    var regex = '.{1,' +width+ '}(\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\S+?(\s|$)');

    return str.match( RegExp(regex, 'g') ).join( brk );

}

Usage:

function wordwrap( str, width, brk, cut ) {
 
    brk = brk || '\n';
    width = width || 75;
    cut = cut || false;
 
    if (!str) { return str; }
 
    var regex = '.{1,' +width+ '}(\s|$)' + (cut ? '|.{' +width+ '}|.+$' : '|\S+?(\s|$)');
 
    return str.match( RegExp(regex, 'g') ).join( brk );
 
}

var n = 50;
var str = "Testando um algoritmo para quebrar esse texto a cada n caracteres sem haver quebra de palavras";

var nova = wordwrap(str, n, "\n");
alert(nova);

Font

    
03.02.2015 / 00:53