Reputation: 10808
I need to remove some redundant '\n's from the end of a csv I'm importing before it divides the lines up into an array (otherwise I get extra empty rows).
public function parseCSV(data:String):Array {
//something to strip linebreaks, \n and \r from end of array
var lines : Array = data.split ( /\R/ );
var preamble : Array = lines.splice(0,trashLength);
var keyArray : Array = lines.splice ( 0, 1 )[0].split ( "," );
var assocArray : Array = [];
for each (var line:String in lines)
{
var valArray : Array = line.split ( "," );
var assoc : Object = {};
for (var i : int = 0; i < keyArray.length; i++)
{
var key : String = keyArray[i];
if (key != null && key != "") assoc[key] = valArray[i];
}
assocArray.push ( assoc );
}
return assocArray;
}
Upvotes: 3
Views: 5560
Reputation: 22604
// normalize line endings to \n, because \r is not recognized as "end of line"
data = data.replace (/\s*\R/g, "\n");
// remove leading and trailing whitespace
data = data.replace (/^\s*|[\t ]+$/gm, "");
Upvotes: 6
Reputation: 2850
I find replace only works on the first occurence of the target in the subject string. You can try array split / join instead.
public static function removeLineBreaks( s:String ) : String
{
return s.split("\r").join("\n");
}
or replace "\n" for "" if you want no delimiter.
Upvotes: 0