Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

chunk/split a string in Javascript without breaking words

Good day,

I would like to know if there is an easy way to chunk/split a string without breaking the words.

Eg:

var input = "Lorem ipsum dolor sit amet, consectetur  adipiscing elit. Proin placerat, nisi nec vulputate scelerisque, metus lectus ultricies massa, et luctus elit libero eu erat. Fusce vitae sem lacus, eu ullamcorper lectus. Lorem ipsum dolor sit amet, consectetur adipiscing elit.";

Should return an array like this if I break at 80 characters long:

var output = ["Lorem ipsum dolor sit amet, consectetur  adipiscing elit. Proin placerat, nisi",
"nec vulputate scelerisque, metus lectus ultricies massa, et luctus elit libero",
"eu erat. Fusce vitae sem lacus, eu ullamcorper lectus. Lorem ipsum dolor sit",
"amet, consectetur adipiscing elit."];

I found that really nice piece of code:

//http://phpjs.org/functions/chunk_split:369
function chunk_split (body, chunklen, end) {
    // Returns split line  
    // 
    // version: 1103.1210
    // discuss at: http://phpjs.org/functions/chunk_split
    // +   original by: Paulo Freitas
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Theriault
    // *     example 1: chunk_split('Hello world!', 1, '*');
    // *     returns 1: 'H*e*l*l*o* *w*o*r*l*d*!*'
    // *     example 2: chunk_split('Hello world!', 10, '*');
    // *     returns 2: 'Hello worl*d!*'
    chunklen = parseInt(chunklen, 10) || 76;
    end = end || '\r\n';

    if (chunklen < 1) {
        return false;
    }

    return body.match(new RegExp(".{0," + chunklen + "}", "g")).join(end);
}

But I really doubt I can modify it so words aren't broken in half. Any tips?

Thank you!

like image 798
Cybrix Avatar asked Jul 09 '11 03:07

Cybrix


People also ask

How can I split a string into two JavaScript?

The split() method splits a string into an array of substrings. The split() method returns the new array. The split() method does not change the original string. If (" ") is used as separator, the string is split between words.

How do I split a string breaking at a particular character?

How to Split a String by Each Character. You can split a string by each character using an empty string('') as the splitter. In the example below, we split the same message using an empty string. The result of the split will be an array containing all the characters in the message string.

How do you split a space in JavaScript?

To split a string by multiple spaces, call the split() method, passing it a regular expression, e.g. str. trim(). split(/\s+/) . The regular expression will split the string on one or more spaces and return an array containing the substrings.


2 Answers

Here's some brute force code that will do it:

function splitIntoLines(input, len) {
    var i;
    var output = [];
    var lineSoFar = "";
    var temp;
    var words = input.split(' ');
    for (i = 0; i < words.length;) {
        // check if adding this word would exceed the len
        temp = addWordOntoLine(lineSoFar, words[i]);
        if (temp.length > len) {
            if (lineSoFar.length == 0) {
                lineSoFar = temp;     // force to put at least one word in each line
                i++;                  // skip past this word now
            }
            output.push(lineSoFar);   // put line into output
            lineSoFar = "";           // init back to empty
        } else {
            lineSoFar = temp;         // take the new word
            i++;                      // skip past this word now
        }
    }
    if (lineSoFar.length > 0) {
        output.push(lineSoFar);
    }
    return(output);
}

function addWordOntoLine(line, word) {
    if (line.length != 0) {
        line += " ";
    }
    return(line += word);
}

If this routine encounters a single word longer than the desired line length, it will put it on a line by itself and will not break it up.

You can play with it here: http://jsfiddle.net/jfriend00/fbaLe/

like image 52
jfriend00 Avatar answered Oct 13 '22 10:10

jfriend00


This builds on @steve's answer but will split the string respecting word break so that the string is never longer than the specified length. This works more like a normal word wrap.

function chunkString(s, len)
{
    var curr = len, prev = 0;

    output = [];

    while(s[curr]) {
      if(s[curr++] == ' ') {
        output.push(s.substring(prev,curr));
        prev = curr;
        curr += len;
      }
      else
      {
        var currReverse = curr;
        do {
            if(s.substring(currReverse - 1, currReverse) == ' ')
            {
                output.push(s.substring(prev,currReverse));
                prev = currReverse;
                curr = currReverse + len;
                break;
            }
            currReverse--;
        } while(currReverse > prev)
      }
    }
    output.push(s.substr(prev)); 
    return output;
}
like image 21
orourkedd Avatar answered Oct 13 '22 09:10

orourkedd