replace all newlines with <br> tags

L

lkrubner

PHP has a function called nl2br() which takes all the newlines in a
string and turns them into break tags <br>. I need to do the same in
javascript. Is this about right? I'm not sure how one is supposed to
reference invisible characters in Javascript strings. I took an example
on the web and tried to modify it to my uses.

function nl2br_js(myString) {
var regX = /\n/gi ;

s = new String(myString);
s = s.replace(regX, "<br /> \n");
return s;
}

After looking around quite a bit using Google, I still couldn't find
out what the gi in the above example is for. What is it?
 
I

Ivo

PHP has a function called nl2br() which takes all the newlines in a
string and turns them into break tags <br>. I need to do the same in
javascript. Is this about right?

function nl2br_js(myString) {
var regX = /\n/gi ;

s = new String(myString);
s = s.replace(regX, "<br /> \n");
return s;
}
After looking around quite a bit using Google, I still couldn't find
out what the gi in the above example is for. What is it?

The 'g' flag makes the expression global so it finds all matches rather than
just the first one.
The 'i' flag makes it case-insensitive so that "a" matches "a" as well as
"A". In your case, the are no letters to match so you can drop the 'i'.
There is a global variable "s" in your function that serves no purpose; also
the variable "regX" is not really needed. Try this cleaned up version:

function nl2br_js(myString){
return myString.replace( /\n/g, '<br />\n' );
}

hth
 
L

lkrubner

Thanks much. This gives me an error "Unterminated regular expression
literal"; I'm sorry to stay I don't know enough about Javascript or
regular expressions to trouble shoot this.
 
L

lkrubner

I rewrite it like this:


function nl2br_js(myString){
var regX = /\\n/g;
var replaceString = '<br> \n';
return myString.replace(regX, replaceString);
}

but now I keep getting "Unterminated string literal" in FireFox. It's
pointing to the space after the br tag.
 
L

lkrubner

Okay, guessing quite randomly I got it to work with this:



function nl2br_js(myString){
var regX = /\\n/g;
var replaceString = '<br> \\n';
return myString.replace(regX, replaceString);
}
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,995
Messages
2,570,236
Members
46,825
Latest member
VernonQuy6

Latest Threads

Top