Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Trying to translate a carriage return into a <br /> html tag in Javascript?

Tags:

javascript

I have an XML feed that im pulling via javascript and translating it into something more HTML friendly, but im caught up on how to translate carriage returns into an html br tag

I tried something like this

text = text.replace('\r','<br />'); 

to no avail..

Any ideas?

like image 235
Mark Avatar asked Aug 07 '11 21:08

Mark


People also ask

How do you do a carriage return in JavaScript?

CR = Carriage Return ( \r , 0x0D in hexadecimal, 13 in decimal) — moves the cursor to the beginning of the line without advancing to the next line.

How do I insert a carriage return in HTML?

The <br> HTML element produces a line break in text (carriage-return). It is useful for writing a poem or an address, where the division of lines is significant.

How do you add BR to a string?

How Can I Add a New String Line? 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

Javascript's replace function only replaces the first occurence if you use a string as the matching criteria. To replace all you can use regex.

Try something like this

text = text.replace(/(\r\n|\n|\r)/g,"<br />");

Hope this helps.

like image 196
Ash Burlaczenko Avatar answered Sep 18 '22 15:09

Ash Burlaczenko