scriptygoddess

02 Dec, 2003

Javascript: Removing new lines ("\n" or "\r") from text

Posted by: Jennifer In: Script snippet

A line break can be created by either a new line (ie. "\n") or a carriage return (ie. "\r"). (more info here)

In my particular use, I had a field that could take several email address that would be seperated by either a comma, semicolon or line break:

(mailform is the form name, and sendto is the text area with the emails)

var emailarray
emailarray = explodeArray(document.mailform.sendto.value,"\n");
if (emailarray.length <= 1) {
emailarray = explodeArray(document.mailform.sendto.value,"\r");
}

if (emailarray.length <= 1) {
emailarray = explodeArray(document.mailform.sendto.value,";");
}
if (emailarray.length <= 1) {
emailarray = explodeArray(document.mailform.sendto.value,",");
}

Then I wanted to run through them and perform another function on each one (but there still seemed to be a carriage or line return that I needed to remove…):

for (var i=0; i< emailarray.length; i++) {
var emailID = emailarray[i];
emailID = replace(emailID,"\n","")
emailID = replace(emailID,"\r","")
…do stuff…
}

The function "replace" is defined like this (found here):

function replace(string,text,by) {
var strLength = string.length, txtLength = text.length;
if ((strLength == 0) || (txtLength == 0)) return string;
var i = string.indexOf(text);
if ((!i) && (text != string.substring(0,txtLength))) return string;
if (i == -1) return string;
var newstr = string.substring(0,i) + by;
if (i+txtLength < strLength)
newstr += replace(string.substring(i+txtLength,strLength),text,by);
return newstr;
}

Also – that "explodeArray" function is defined here:

function explodeArray(item,delimiter) {
tempArray=new Array(1);
var Count=0;
var tempString=new String(item);
while (tempString.indexOf(delimiter)>0) {
tempArray[Count]=tempString.substr(0,tempString.indexOf(delimiter));
tempString=tempString.substr(tempString.indexOf(delimiter)+1,tempString.length-tempString.indexOf(delimiter)+1);
Count=Count+1
}
tempArray[Count]=tempString;
return tempArray;
}

I'm not sure of the source of that one – I may have linked to it previously…

No Responses to "Javascript: Removing new lines ("\n" or "\r") from text"

Comments are closed.

Featured Sponsors

Genesis Framework for WordPress

Advertise Here


  • Scott: Just moved changed the site URL as WP's installed in a subfolder. Cookie clearance worked for me. Thanks!
  • Stephen Lareau: Hi great blog thanks. Just thought I would add that it helps to put target = like this:1-800-555-1212 and
  • Cord Blomquist: Jennifer, you may want to check out tp2wp.com, a new service my company just launched that converts TypePad and Movable Type export files into WordPre

About


Advertisements