By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
459,568 Members | 1,688 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 459,568 IT Pros & Developers. It's quick & easy.

replace all newlines with <br> tags

P: n/a
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?

Jul 23 '05 #1
Share this Question
Share on Google+
4 Replies


P: n/a
Ivo
<lk******@geocities.com> wrote
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
--
Ivo
Jul 23 '05 #2

P: n/a
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.

Jul 23 '05 #3

P: n/a
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.

Jul 23 '05 #4

P: n/a
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);
}

Jul 23 '05 #5

This discussion thread is closed

Replies have been disabled for this discussion.