Tuesday, August 09, 2005

Replacing Line Feeds in IE and Mozilla

Line breaks, carriage returns, new lines, form feeds, whatever you might think of them as, browsers have their own ideas. I'm talking specifically about the character(s) produced when you hit Enter within a textarea and then try to manipulate the value of that textarea with JavaScript using regular expressions.

IE (internet explorer) on a PC
\r\n
Firefox (mozzilla) on a PC
\n

So, if you wanted to replace all the "line feeds" in a variable whose value was pulled from a textarea with a single space this is the code you would need:

val = val.replace(/\r\n/g," ");
val = val.replace(/\n/g," ");

On a related note, IE also has a funny idea about what character a single space is represented by when written to the page from a database (but not when typed with the space bar). If you want to strip out all of the spaces from a field in IE try this bit of hex:

val = val.replace(/[\xA0]/g,"");

That concludes this geeky interlude. Now back to our regularly scheduled nerdiness.

No comments: