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?
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.
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.
The array elements are divided into newline using '\r\n'.
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.
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With