Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I replace all line breaks in a string with <br /> elements?

Tags:

javascript

How can I read the line break from a value with JavaScript and replace all the line breaks with <br /> elements?

Example:

A variable passed from PHP as below:

  "This is man.       Man like dog.      Man like to drink.       Man is the king." 

I would like my result to look something like this after the JavaScript converts it:

  "This is man<br /><br />Man like dog.<br />Man like to drink.<br /><br />Man is the king." 
like image 246
Jin Yong Avatar asked Apr 24 '09 04:04

Jin Yong


People also ask

How do you remove a line break in a string?

Use the String. replace() method to remove all line breaks from a string, e.g. str. replace(/[\r\n]/gm, ''); . The replace() method will remove all line breaks from the string by replacing them with an empty string.


1 Answers

This will turn all returns into HTML

str = str.replace(/(?:\r\n|\r|\n)/g, '<br>'); 

In case you wonder what ?: means. It is called a non-capturing group. It means that group of regex within the parentheses won't be saved in memory to be referenced later. You can check out these threads for more information:
https://stackoverflow.com/a/11530881/5042169 https://stackoverflow.com/a/36524555/5042169

like image 83
eyelidlessness Avatar answered Nov 01 '22 18:11

eyelidlessness