How to remove line breaks from a string?

I need to remove some redundant '\ n from the end of the imported csv before it divides the lines into an array (otherwise I get extra empty lines).

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;
}
+3
source share
2 answers
// 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, ""); 
+6
source

I find replacing only works on the first entry of the goal into the subject line. Instead, you can try split split / join.

public static function removeLineBreaks( s:String ) : String 
{ 
    return s.split("\r").join("\n");
}

or replace "\ n" with "" if you do not want a divisor.

0
source

Source: https://habr.com/ru/post/1793525/


All Articles