Page 1 of 1
Converting '\n's into '<br/>'s
Posted: Wed May 23, 2007 3:57 pm
by JellyFish
How do I take a string an replace all the '\n' characters with '<br/>' tags in JavaScript?
The string comes from a textarea element and whenever I enter a new line with the return/enter key it adds a \n character right? So what I want to do is take all the new lines and replace them with <br/> tags.
I think this will require some regular expressions...
Thanks for reading.

Posted: Wed May 23, 2007 4:04 pm
by Luke
Posted: Wed May 23, 2007 4:15 pm
by JellyFish
This is good. But I don't understand, does it remove the newlines or does it just add break tags?
I've figured out how I could do it with JS:
Code: Select all
str = str.replace(/\n/, "<br />");
Quite simple really. But how could I take those breaks and replace them with newlines (the opposite) in php?
EDIT: I tested nl2br() and apparently this just adds break tags. I'm looking for replacing them.
I did this with javascript, successfully. Is there a way I can do it with PHP, just to know my options?
(This is becoming more off a php thread...)
Posted: Wed May 23, 2007 4:19 pm
by Benjamin
str_replace() preg_replace()
Posted: Wed May 23, 2007 4:32 pm
by JellyFish
Sorry for the confusion but, I'm thinking I might want to go with javascript when replacing breaks with newlines.
I'm trying something like:
Code: Select all
str = str.replace(/<br \/>/, "\n");
This isn't working though.
EDIT: Wait... It's working. Just need to add a global flag (.../g).
I Think I'm done here.
Thanks for all the help guys. I appreciate your posts.
Cheers.
Posted: Wed May 23, 2007 5:26 pm
by Luke
I apologize, I didn't notice this was in client side
