Converting '\n's into '<br/>'s

JavaScript and client side scripting.

Moderator: General Moderators

Post Reply
User avatar
JellyFish
DevNet Resident
Posts: 1361
Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA

Converting '\n's into '<br/>'s

Post 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. :D
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

User avatar
JellyFish
DevNet Resident
Posts: 1361
Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA

Post 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...)
Last edited by JellyFish on Wed May 23, 2007 4:19 pm, edited 1 time in total.
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post by Benjamin »

str_replace() preg_replace()
User avatar
JellyFish
DevNet Resident
Posts: 1361
Joined: Tue Feb 14, 2006 7:18 pm
Location: San Diego, CA

Post 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. :D

Cheers.
User avatar
Luke
The Ninja Space Mod
Posts: 6424
Joined: Fri Aug 05, 2005 1:53 pm
Location: Paradise, CA

Post by Luke »

I apologize, I didn't notice this was in client side :oops:
Post Reply