How to insert a line break after every 80 characters

I have a very long string.

I want to add <br/> after every 80 characters so that it can display well in the internal HTML file.

Is there an easy way?

+4
source share
4 answers

Do this with long_string.replace(/(.{80})/g, "$1<br>");

Check here: http://jsfiddle.net/x2YJp/

+5
source

Here's an academic edition (it's also faster than a regular expression ):

 function fold(input, lineSize, lineArray) { lineArray = lineArray || []; if (input.length <= lineSize) { lineArray.push(input); return lineArray; } lineArray.push(input.substring(0, lineSize)); var tail = input.substring(lineSize); return fold(tail, lineSize, lineArray); } 

Using:

 var arrayOfLines = fold(longString, 80); var foldedString = arrayOfLines.join('<br/>'); 

Another cool thing about this approach: you can easily wrap in spaces.

Here's the fiddle that does this.

+3
source

Try something like:

 yourString = yourString.replace(/(.{1,80})/g, '$1<br/>') 

You can also just set the width of the containing text element to 80em . (it will not match exactly 80 characters, since em is the width of the letter m , so you can set it a bit lower)

+3
source

replace 0,1 with 0,80 and connect ('is') with '<br />'

 console.log("google is very fast".match(new RegExp(".{0,1}", "g")).join('is')); 
+1
source

Source: https://habr.com/ru/post/1493785/


All Articles