Thursday, 1 April 2010

JavaScript to remove newline characters from a string

Using a regular expression


function removeNL(s){
return s.replace(/[\n\r\t]/g, ""); //replaces NewLine or CarriageReturn or Tab with empty string.
}


Call

s.replace(/[\n]/g, "");

to remove all newline characters.


////////////////////////

function removeNL(s) {
/*
** Remove NewLine, CarriageReturn and Tab characters from a String
** s string to be processed
** returns new string
*/
r = "";
for (i=0; i < s.length; i++) {
if (s.charAt(i) != '\n' &&
s.charAt(i) != '\r' &&
s.charAt(i) != '\t') {
r += s.charAt(i);
}
}
return r;
}

No comments:

Post a Comment