Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert a newline character after every 200 characters with jQuery

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?

like image 765
Nishant Kumar Avatar asked Dec 01 '10 05:12

Nishant Kumar


People also ask

How can I insert a character after every n characters in JavaScript?

To insert a character after every N characters, call the replace() method on the string, passing it the following regular expression - str. replace(/. {2}/g, '$&c') . The replace method will replace every 2 characters with the characters plus the provided replacement.

How do I add a new line character?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

How do you add a new line to an array?

The array elements are divided into newline using '\r\n'.

Can we use \n in JavaScript?

The newline character is \n in JavaScript and many other languages. All you need to do is add \n character whenever you require a line break to add a new line to a string.


1 Answers

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;
}
like image 126
casablanca Avatar answered Oct 02 '22 22:10

casablanca