Wrap Text In JavaScript
Asked Answered
A

14

42

I am new to JavaScript and jQuery.

I have a variable named as str in JavaScript and it contains very long text, saying something like

"A quick brown fox jumps over a lazy dog". 

I want to wrap it and assign it to the same variable str by inserting the proper \n or br/ tags at the correct places.

I don't want to use CSS etc. Could you please tell me how to do it with a proper function in JavaScript which takes the str and returns the proper formatted text to it?

Something like:

str = somefunction(str, maxchar);

I tried a lot but unfortunately nothing turned up the way I wanted it to be! :(

Any help will be much appreciated...

Adai answered 23/1, 2013 at 16:41 Comment(5)
How do you know which places are the "correct" places?Satem
You want a new-line every n characters?Alenealenson
@OP Code must be wrapped in a code block, don't remove the edit(s).Fungal
Wouldn't the wrapping be done automatically if your limit the with of the element which it is written in?Cincture
maybe a wordwrap module would help?Viborg
G
33

This should insert a line break at the nearest whitespace of maxChar:

str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It w as popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

str = wordWrap(str, 40);

function wordWrap(str, maxWidth) {
    var newLineStr = "\n"; done = false; res = '';
    while (str.length > maxWidth) {                 
        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);
        }

    }

    return res + str;
}

function testWhite(x) {
    var white = new RegExp(/^\s$/);
    return white.test(x.charAt(0));
};
Gabrielagabriele answered 23/1, 2013 at 19:5 Comment(5)
yeah it works but for some capital letters it disrupts the aligment of page have you noticed that ??Tarantula
this code is cutting some last words from the text inserted does anyone has modified codeTarantula
this works but will break long words without spaces (like links) which might be not desiderableScutage
Code worked fine for me. you might get warning or error especially when you are working with angular or react. To fix just work on linting and declaration of variablesWindfall
still a great awnser, I just used it but updated the code a little to maintain user inpute'd "enters/returns". If anyone else needs something like that check out: codepen.io/hozeis/pen/JjrePdEJipijapa
J
79

Although this question is quite old, many solutions provided so far are more complicated and expensive than necessary, as user2257198 pointed out - This is completely solvable with a short one-line regular expression.

However I found some issues with his solution including: wrapping after the max width rather than before, breaking on chars not explicitly included in the character class and not considering existing newline chars causing the start of paragraphs to be chopped mid-line.

Which led me to write my own solution:

// Static Width (Plain Regex)
const wrap = (s) => s.replace(
    /(?![^\n]{1,32}$)([^\n]{1,32})\s/g, '$1\n'
);

// Dynamic Width (Build Regex)
const wrap = (s, w) => s.replace(
    new RegExp(`(?![^\\n]{1,${w}}$)([^\\n]{1,${w}})\\s`, 'g'), '$1\n'
);

Bonus Features

  • Handles any char that's not a newline (e.g code).
  • Handles existing newlines properly (e.g paragraphs).
  • Prevents pushing spaces onto beginning of newlines.
  • Prevents adding unnecessary newline to end of string.

Explanation

The main concept is simply to find contiguous sequences of chars that do not contain new-lines [^\n], up to the desired length, e.g 32 {1,32}. By using negation ^ in the character class it is far more permissive, avoiding missing things like punctuation that would otherwise have to be explicitly added:

str.replace(/([^\n]{1,32})/g, '[$1]\n');
// Matches wrapped in [] to help visualise

"[Lorem ipsum dolor sit amet, cons]
[ectetur adipiscing elit, sed do ]
[eiusmod tempor incididunt ut lab]
[ore et dolore magna aliqua.]
"

So far this only slices the string at exactly 32 chars. It works because it's own newline insertions mark the start of each sequence after the first.

To break on words, a qualifier is needed after the greedy quantifier {1,32} to prevent it from choosing sequences ending in the middle of a word. A word-break char \b can cause spaces at the start of new lines, so a white-space char \s must be used instead. It must also be placed outside the group so it's eaten, to prevent increasing the max width by 1 char:

str.replace(/([^\n]{1,32})\s/g, '[$1]\n');
// Matches wrapped in [] to help visualise

"[Lorem ipsum dolor sit amet,]
[consectetur adipiscing elit, sed]
[do eiusmod tempor incididunt ut]
[labore et dolore magna]
aliqua."

Now it breaks on words before the limit, but the last word and period was not matched in the last sequence because there is no terminating space.

An "or end-of-string" option (\s|$) could be added to the white-space to extend the match, but it would be even better to prevent matching the last line at all because it causes an unnecessary new-line to be inserted at the end. To achieve this a negative look-ahead of exactly the same sequence can be added before, but using an end-of-string char instead of a white-space char:

str.replace(/(?![^\n]{1,32}$)([^\n]{1,32})\s/g, '[$1]\n');
// Matches wrapped in [] to help visualise

"[Lorem ipsum dolor sit amet,]
[consectetur adipiscing elit, sed]
[do eiusmod tempor incididunt ut]
labore et dolore magna aliqua."
Jones answered 24/7, 2018 at 20:5 Comment(11)
So good! I've been looking for this type of functionality to produce a pseudo-two column format within a text area and it worked perfectly. Thank you.Igenia
I would like to include the last line up to the period in the array, is that possible?Igenia
How would one add an indent at the start of broken lines?Monolingual
I managed to do it like this: str.concat("\n").split(/(?![^\n]{1,71}$)([^\n]{1,71})\s/g).filter((_, i) => i % 2 === 1).map((s, i) => (i > 0 ? ${s}` : s)).join("\n")` (I know, its not much to look at)Monolingual
@Igenia I achieved that with str.concat("\n").replace(/(?![^\n]{1,32}$)([^\n]{1,32})\s/g, '[$1]\n');Monolingual
This is great but what id the word is larger than the maximum, it is not captured at all.Ybarra
I tried this with long words and had no problem. In my case I have a calculation for the width and I will probably try to make that either the result of my calculation or the length of the longest word (whichever is greater).Celisse
However I wanted to try something else. I wanted to support hyphens. This would allow me to place a hyphen where I'd like the text to be split if necessary. My result caused the hyphen to be left in even if the split was not made, so I added a second replace to locate and remove unused hyphens. const wrap = function (s, w) { var wrapped = s.replace(new RegExp((?![^\\n]{1,${w}}$)(([^\\n]{1,${w}}-)|([^\n]{1,${w}})(?:\\s)), 'g'), '$1\n'); return wrapped.replace(new RegExp('(?!-$)(-)', 'gm'), ''); }Celisse
I changed my expression a little making it more compact and behave better. (?![^\\n]{1,${width}}$)(([^\n]{1,${width}})((?:\\s)|-))Celisse
@Igenia Yes you can replace the string to return text instead of an array i.e. change [$1]\n to $1\n in the above expression and then use the split function to split the string using the same delimiter i.e stringArray = wrappedStr.split('\n').Detergent
Perfect solution for a problem often overly contemplated.Alost
G
33

This should insert a line break at the nearest whitespace of maxChar:

str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It w as popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

str = wordWrap(str, 40);

function wordWrap(str, maxWidth) {
    var newLineStr = "\n"; done = false; res = '';
    while (str.length > maxWidth) {                 
        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);
        }

    }

    return res + str;
}

function testWhite(x) {
    var white = new RegExp(/^\s$/);
    return white.test(x.charAt(0));
};
Gabrielagabriele answered 23/1, 2013 at 19:5 Comment(5)
yeah it works but for some capital letters it disrupts the aligment of page have you noticed that ??Tarantula
this code is cutting some last words from the text inserted does anyone has modified codeTarantula
this works but will break long words without spaces (like links) which might be not desiderableScutage
Code worked fine for me. you might get warning or error especially when you are working with angular or react. To fix just work on linting and declaration of variablesWindfall
still a great awnser, I just used it but updated the code a little to maintain user inpute'd "enters/returns". If anyone else needs something like that check out: codepen.io/hozeis/pen/JjrePdEJipijapa
C
13

Here is a little shorter solution:

var str = "This is a very long line of text that we are going to use in this example to divide it into rows of maximum 40 chars."

var result = stringDivider(str, 40, "<br/>\n");
console.log(result);

function stringDivider(str, width, spaceReplacer) {
    if (str.length>width) {
        var p=width
        for (;p>0 && str[p]!=' ';p--) {
        }
        if (p>0) {
            var left = str.substring(0, p);
            var right = str.substring(p+1);
            return left + spaceReplacer + stringDivider(right, width, spaceReplacer);
        }
    }
    return str;
}

This function uses recursion to solve the problem.

Cincture answered 24/1, 2013 at 13:20 Comment(3)
Thank you! I needed a prefix and a postfix, and to do any white space such as tab, so I updated your scheme and put it on this jsfiddle: jsfiddle.net/rhyous/q409e7ej/1Extortioner
@Rhyous, nice but your last row doesn't get the prefix and postfix, neither does a short row. Might be by design, might not. :)Cincture
Thank you. We found those bugs in implementation and resolved them, I didn't get around to updating, so thank you for doing so!Extortioner
T
9

My version. It returns a array of lines instead of a string as it is more flexible on what line separators you want to use (like newline or html BR).

function wordWrapToStringList (text, maxLength) {
    var result = [], line = [];
    var length = 0;
    text.split(" ").forEach(function(word) {
        if ((length + word.length) >= maxLength) {
            result.push(line.join(" "));
            line = []; length = 0;
        }
        length += word.length + 1;
        line.push(word);
    });
    if (line.length > 0) {
        result.push(line.join(" "));
    }
    return result;
};

To convert the line array to string to a string:

wordWrapToStringList(textToWrap, 80).join('<br/>');

Please note that it only does word wrap and will not break long words, and it's probably not the fastest.

Tayib answered 1/8, 2016 at 23:42 Comment(1)
This is perfect for code templates (i.e. auto-generating classfiles) if you have a variable e.g. description that you want to break up and need to wrap each line -- thank youReferendum
L
3

Many behaviours like this can be achieved as a single-liner using regular expressions (using non-greedy quantifiers with a minimum number of matching characters, or greedy quantifiers with a maximum number of characters, depending what behaviour you need).

Below, a non-greedy global replace is shown working within the Node V8 REPL, so you can see the command and the result. However the same should work in a browser.

This pattern searches for at least 10 characters matching a defined group ( \w meaning word characters, \s meaning whitespace characters), and anchors the pattern against a \b word boundary. It then uses a backreference to replace the original match with one having a newline appended (in this case, optionally replacing a space character which is not captured in the bracketed backreference).

> s = "This is a paragraph with several words in it."
'This is a paragraph with several words in it.'
> s.replace(/([\w\s]{10,}?)\s?\b/g, "$1\n")
'This is a \nparagraph \nwith several\nwords in it\n.'

In the original poster's requested format this could look like...

var str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It w as popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

function wordWrap(text,width){
    var re = new RegExp("([\\w\\s]{" + (width - 2) + ",}?\\w)\\s?\\b", "g")
    return text.replace(re,"$1\n")
}

> wordWrap(str,40)
'Lorem Ipsum is simply dummy text of the\nprinting and typesetting industry. Lorem Ipsum has been the industry\'s standard dummy text ever since the 1500s\n, when an unknown printer took a galley of\ntype and scrambled it to make a type specimen\nbook. It has survived not only five centuries\n, but also the leap into electronic typesetting\n, remaining essentially unchanged. It w as popularised in the 1960s with the\nrelease of Letraset sheets containing Lorem\nIpsum passages, and more recently with desktop publishing\nsoftware like Aldus PageMaker including\nversions of Lorem Ipsum.'
Lowpressure answered 26/11, 2015 at 14:45 Comment(1)
Warning: this does not split when the word length is greater than 10Roving
I
2

My variant. It keeps words intact, so it might not always meet the maxChars criterium.

function wrapText(text, maxChars) {
        var ret = [];
        var words = text.split(/\b/);

        var currentLine = '';
        var lastWhite = '';
        words.forEach(function(d) {
            var prev = currentLine;
            currentLine += lastWhite + d;

            var l = currentLine.length;

            if (l > maxChars) {
                ret.push(prev.trim());
                currentLine = d;
                lastWhite = '';
            } else {
                var m = currentLine.match(/(.*)(\s+)$/);
                lastWhite = (m && m.length === 3 && m[2]) || '';
                currentLine = (m && m.length === 3 && m[1]) || currentLine;
            }
        });

        if (currentLine) {
            ret.push(currentLine.trim());
        }

        return ret.join("\n");
    }
Iselaisenberg answered 9/10, 2014 at 14:48 Comment(0)
S
1

Here's an extended answer based on javabeangrinder's solution that also wraps text for multi-paragraph input:

  function wordWrap(str, width, delimiter) {
    // use this on single lines of text only

    if (str.length>width) {
      var p=width
      for (; p > 0 && str[p] != ' '; p--) {
      }
      if (p > 0) {
        var left = str.substring(0, p);
        var right = str.substring(p + 1);
        return left + delimiter + wordWrap(right, width, delimiter);
      }
    }
    return str;
  }

  function multiParagraphWordWrap(str, width, delimiter) {
    // use this on multi-paragraph lines of text

    var arr = str.split(delimiter);

    for (var i = 0; i < arr.length; i++) {
        if (arr[i].length > width)
          arr[i] = wordWrap(arr[i], width, delimiter);
    }

    return arr.join(delimiter);
  }
Succor answered 25/5, 2017 at 18:56 Comment(1)
Awesome - this was the only function that worked properly for me. Just a small tip - browsers (with CSS) seem to break the words by '-' also. With this small addition it can be made to behave the same way.Unseasoned
J
1

After looking for the perfect solution using regex and other implementations. I decided to right my own. It is not perfect however worked nice for my case, maybe it does not work properly when you have all your text in Upper case.

function breakTextNicely(text, limit, breakpoints) {

      var parts = text.split(' ');
      var lines = [];
      text = parts[0];
      parts.shift();

      while (parts.length > 0) {
        var newText = `${text} ${parts[0]}`;

        if (newText.length > limit) {
          lines.push(`${text}\n`);
          breakpoints--;

          if (breakpoints === 0) {
            lines.push(parts.join(' '));
            break;
          } else {
          	text = parts[0];
    	  }
        } else {
          text = newText;
        }
    	  parts.shift();
      }

      if (lines.length === 0) {
        return text;
      } else {
        return lines.join('');
      }
    }

    var mytext = 'this is my long text that you can break into multiple line sizes';
    console.log( breakTextNicely(mytext, 20, 3) );
Journal answered 1/9, 2017 at 16:52 Comment(1)
will fail with this text var mytext = 'this is my long multiple line sizes asdsddghfssssssssghfghfghfghhhhhhhhhhhhhhhk asdsddghfssssssssghfghfghfghhhhhhhhhhhhhhhk it wont break aby more form here';Scutage
U
0

I modified ieeehh's answer, by adding an optional third parameter. If a delimiter is supplied, the text will be joined automatically.

I also hyphenated broken words.

const str = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It w as popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";

console.log(wordWrap(str).join('  |  ')); // Default:  max 80 | string[]
console.log(wordWrap(str, 40, '\n'));     // Override: max 40 | string (join by \n)

/**
 * Wraps a string at a max character width.
 * 
 * If the delimiter is set, the result will be a delimited string;
 * else, the lines as a string array.
 *
 * @param {string} text - Text to be wrapped
 * @param {number} [maxWidth=80] - Maximum characters per line
 * @param {string | null | undefined} [delimiter=null] - Joins the lines if set
 * @returns {string | string[]} - The joined lines as a string, or an array
 */
function wordWrap(text, maxWidth = 80, delimiter = null) {
  let lines = [], found, i;
  while (text.length > maxWidth) {
    found = false;
    // Inserts new line at first whitespace of the line (right to left)
    for (i = maxWidth - 1; i >= 0 && !found; i--) {
      if (/\s/.test(text.charAt(i))) {
        lines.push(text.slice(0, i))
        text = text.slice(i + 1);
        found = true;
      }
    }
    // Inserts new line at maxWidth position, since the word is too long to wrap
    if (!found) {
      lines.push(text.slice(0, maxWidth - 1) + '-') // Hyphenate
      text = text.slice(maxWidth - 1);
    }
  }
  if (text) lines.push(text)
  return delimiter ? lines.join(delimiter) : lines;
}
.as-console-wrapper { top: 0; max-height: 100% !important; }
Uttermost answered 31/8, 2023 at 17:48 Comment(0)
D
0

There are many ways to do this and though the answer from Thomas Brierley will fit most use cases, pure regex is not ideal with larger text of multiline structures. The other answers may lead to final lines being omitted and will not work in a universal manner.

Instead of using regex, one will be better off lexing the text content and construct the wrap logic on character count basis. Albeit this solution may not be as elegant as the regex solution offered but it will output concise results in a performant manner while respecting paragraphical occurrences and allowing custom newline breaks. I have put together a small sandbox example of the code in action:

See the Flems Playground for demo.

Code

function wrap (input: string, { limit = 80, breaks = '\n', join = true } = {}) {
  
  const lexed: string[] = []
  const regex: RegExp = /([\t\v\r \u00a0\u2000-\u200b\u2028-\u2029\u3000]+)/g;
  const words: string[] = input.trim().replace(regex, ' ').split(/(\s+)/);  
  
  for (let i=0,n=1,p=0,w=0,s=words.length - 1; i < s; i++, n <= s ? ++n : n) {

    if (/\n+/.test(words[i])) {
      lexed.push(words[i].length > 1 ? words[i].slice(1) : words[i]);
      p = n;
      w = 0;
    } else { 
      w = w + words[i].length;
      if (w + words[n].length > limit) {
        lexed.push(words.slice(p, n).join('').trim(),  breaks);
        p = n;
        w = 0;
      } 
    }
    
    if(n === s) {
      lexed.push(words.slice(p).join(''))
      break
    }
  }
  
  return join ? lexed.join('') : lexed;
}

Usage

wrap('add your long string to wrap', {
  limit: 80,     // wrap limit
  breaks: '\n',  // newline characters
  join: true     // Whether or not to join or return array
})

Breakdown

The main takeaways are as follows:

  • Extraneous whitespace will be equalized. e.g: foo bar > foo bar
  • Trim start and end are applied to input
  • Newlines are respected
  • Optionally return as a string or string list (i.e: string[])
  • Accepts custom line break characters, e.g: \n or <br> etc
Dehorn answered 14/10, 2023 at 7:9 Comment(0)
T
0

The answer from Thomas Brierley was very helpful, but not quite enough. I wanted to hard-wrap text to lines of 79 characters, respecting whitespace if possible but never exceeding 79 characters. That answer doesn't handle very long "words" (such as a URL) at all.

The simple solution is to perform two hard wraps: First insert breaks within long words, then insert breaks within long lines. Remember to use 1 character less than your target line length to account for the \n newline character itself.

let text = 'INDEPENDENT AND UNBIASED - ACROSS BROWSERS AND TECHNOLOGIES\nThis guiding principle has made MDN Web Docs the go-to repository of independent information for developers, regardless of brand, browser or platform. We are an open community of devs, writers, and other technologists building resources for a better Web, with over 17 million monthly MDN users from all over the world. Anyone can contribute, and each of the 45,000 individuals who have done so over the past decades has strengthened and improved the resource. We also receive content contributions from our partners, including Microsoft, Google, Samsung, Igalia, W3C and others. Together we continue to drive innovation on the Web and serve the common good.\n\nACCURATE AND VETTED FOR QUALITY\nThrough our GitHub documentation repository, contributors can make changes, submit pull requests, have their contributions reviewed and then merged with existing content. Through this workflow, we welcome the vast knowledge and experience of our developer community while maintaining a high level of quality, accurate content.\n\nPortions of this content are ©1998–2023 by individual mozilla.org contributors. Content available under a Creative Commons license: https://developer.mozilla.org/en-US/docs/MDN/Writing_guidelines/Attrib_copyright_license';

let lines = text
    // Break long words at exactly 78 characters
    .replace(/([^\s]{78})/g, '$1\n')
    // Break long lines honoring whitespace
    .replace(/([^\n]{1,78})(\s|$)/g, '$1\n')
    .trim()
    .split('\n');

The end result is an array of lines (shown here with the length +1 to account for the trailing \n newline). lines

Thomasinethomason answered 7/12, 2023 at 19:27 Comment(0)
B
-1

I am using a simple ajax and javascript practise to do that

var protest = "France is actually the worlds most bad country consisting of people and president full of mentaly gone persons and the people there are causing the disturbance and very much problem in the whole of the world.France be aware that one day there will be no france but you will be highly abused of your bad acts.France go to hell.";

protest = protest.replace(/(.{100})/g, "$1<br>");

document.write(protest);
Brann answered 3/11, 2020 at 15:38 Comment(0)
I
-1
const newString = string.split(' ').reduce((acc, curr) => {
  if(acc[acc.length - 1].length > 100) {
    acc[acc.length - 1] = acc[acc.length - 1].concat(" ").concat(curr);
    acc.push(""); // new line
  } else {
    acc[acc.length - 1] = acc[acc.length - 1].concat(" ").concat(curr);
  }
  return acc;
}, [""]).join("\n");

console.log(newString)
Interactive answered 16/6, 2021 at 1:36 Comment(0)
S
-2
function GetWrapedText(text, maxlength) {    
    var resultText = [""];
    var len = text.length;    
    if (maxlength >= len) {
        return text;
    }
    else {
        var totalStrCount = parseInt(len / maxlength);
        if (len % maxlength != 0) {
            totalStrCount++
        }

        for (var i = 0; i < totalStrCount; i++) {
            if (i == totalStrCount - 1) {
                resultText.push(text);
            }
            else {
                var strPiece = text.substring(0, maxlength - 1);
                resultText.push(strPiece);
                resultText.push("<br>");
                text = text.substring(maxlength - 1, text.length);
            }
        }
    }
    return resultText.join("");
}
Sheetfed answered 6/2, 2013 at 14:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.