Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

breaking a string into different lines?

Tags:

javascript

In javascript how to break my string if it exceeds 25 characters into two lines , if my string contain 75 character i want to get the string to three lines of 25 character.

thanks in advance

like image 847
kiran Avatar asked Apr 16 '26 10:04

kiran


1 Answers

That's really easy to accomplish with a regular expression:

var text = '75 characters long (really!) — well... maybe not, but you get the picture.',
    broken;
broken = text.replace(/([^\0]{25})/g, '$1\n');

As demonstrated here: http://jsbin.com/ajiyo/3.

Edit: To explain the regular expression: it will match any string of characters (the collection of every character except NUL), that is 25 characters long.

The parentheses () mean that this portion should be captured, and the '$1' part of the second argument (the replacement string) refers to that first capture.

Every string of 25 characters found will be replaced by 'itself plus a newline'. If the remainder is less than 25 characters, it will not be matched but left alone.

2nd edit: Brock is right, the dot loses its special meaning when in square brackets. I've replaced that by all non-NUL characters, since I don't expect NUL characters in a text string.

like image 182
Martijn Avatar answered Apr 18 '26 01:04

Martijn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!