17

I have a textbox that I use to insert some information. I want to insert a newline character after every 200 characters using jQuery or JavaScript.

For instance:

aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa

In this example, I want to insert a newline chracter after every 200 characters. How can I do this?

Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
Nishant Kumar
  • 5,995
  • 19
  • 69
  • 95

8 Answers8

26

You can do this is just one line of code.

var newStr = str.replace(/(.{200})/g, "$1\n")

Works well if you want prefixes or postfixes on every line as well

var newStr = str.replace(/(.{200})/g, "prefix- $1 -postfix\n")
Will Morgan
  • 4,470
  • 5
  • 29
  • 42
Martin K
  • 782
  • 7
  • 13
26

Break the string after every 200 characters, add a newline, and repeat this process with the remaining string:

function addNewlines(str) {
  var result = '';
  while (str.length > 0) {
    result += str.substring(0, 200) + '\n';
    str = str.substring(200);
  }
  return result;
}
casablanca
  • 69,683
  • 7
  • 133
  • 150
  • 1
    Could be improved by giving more options and using hyphens when starting a new line. See my improvements in my [comparison](http://jsfiddle.net/tLp7P/) – James Cameron Jun 05 '14 at 10:35
  • I used this method to do the same thing that asked in the question. What I was found is there are additional space is present after using the method. I used trim(), but it makes the value is meaningless. Do you have any idea to avoid those spaces. before - ER Throttle Position ER Throttle Position ER Throt after - ER Throttle Pos ition ER Thrott le Position ER Throt – Linidu Praneeth Gunathilaka Nov 05 '21 at 10:06
  • var columnValue = 'ER Throttle Position ER Throttle Position ER Throt'; var result = ''; while (columnValue.length > 0) { var sub = columnValue.substring(0, 15) + '\n'; result += sub; columnValue = columnValue.substring(15); } columnValue = result; return columnValue; – Linidu Praneeth Gunathilaka Nov 05 '21 at 10:09
3

Try this function it is just plain javascript. It takes the string and the number of characters to break after.

function addBreaks(s,c) {
    var l = s.length;
    var i = 0;
    while (l > c) {
        l = l-c;
        i=i+c;
        s = s.substring(0,c)+"\n"+s.substring(c);
    }
    return s;
}
var a=' aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa';

addBreaks(a,200);
Tom Belote
  • 590
  • 3
  • 8
1

http://javascript.about.com/library/blchunk.htm

alxndr
  • 3,851
  • 3
  • 34
  • 35
1

If user is entering that text you can do the following:

  1. Implement keydown event and whenever you reach the 200 count... insert a new line character and append it again.

  2. If you are getting it from database, just before setting the value read that string and insert a new line character manually.

Jefferson
  • 794
  • 10
  • 24
kobe
  • 15,671
  • 15
  • 64
  • 91
1
 $("#text").keyup(function()//Detect keypress in the textarea
    {
        var text_area_box =$(this).val();//Get the values in the textarea
        var max_numb_of_words = 200;//Set the Maximum Number of chars
        var main = text_area_box.length*100;//Multiply the lenght on words x 100

        var value= (main / max_numb_of_words);//Divide it by the Max numb of words previously declared

        if(text_area_box.length >= max_numb_of_words) {
            //add break
        }
        return false;
        });
switz
  • 24,384
  • 25
  • 76
  • 101
0

<!DOCTYPE html>
<html>
<head>
<title>HTML textarea Tag</title>
<script
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>

<body>

        <textarea data-row-maxlength="200" data-limit-row-len="true"></textarea>

</body>
</html>

<script>
    $("textarea[data-limit-row-len=true]").on("input focus keydown keyup",
            function(event) {
                var maxlength = $(this).data("row-maxlength");

                var text = $(this).val();
                var lines = text.split(/(\r\n|\n|\r)/gm);
                for (var i = 0; i < lines.length; i++) {
                    if (lines[i].length > maxlength) {
                        lines[i] = lines[i].substring(0, maxlength) + "\n";
                    }
                }
                $(this).val(lines.join(''));
            });
</script>
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Jun 02 '22 at 03:57
0

To anyone who came here looking to add the new line after each word rather than abruptly right at the character:

function addWordNewLine(str, breakpoint=80){
    var words = str.split(" ");
    var numChars = 0;
    var mult = 1;
    for(var i = 0; i < words.length; i++){
        numChars += words[i].length;

        // if( we hit a multiple of our breakpoint number )
        if(numChars > breakpoint * mult){
            words[i] += '\n';
            mult++;
        }
    }
    // As we re-arrange our text, make sure that a newline isn't followed
    // with a space so that there's no odd single-space indenting
    var p = words.join(" ").replaceAll("\n ", "\n");
    return p;
}

var str = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.";
var formatted = addWordNewLine(str); // default breaks after word after every 80 chars
var wideFormatted = addWordNewLine(str, 200); // breaks after word after every 200 chars