vinu
vinu

Reputation: 191

Removing last comma

I read content from a file and then write it another file after editing . While editing , for each read line i put a comma at the end of line and then write it to the file. For the last read line i do not want to write a comma. How should i do it.?

 while(!inputFile.AtEndOfStream){
    var readLine =  inputFile.ReadLine();
    var omitChars = new RegExp("#define").test(readLine);
    if(omitChars==1){
        var stringReadPosition = readLine.substr(8);
        var finalString = stringReadPosition.replace(/\s+/g, ': ');
              asd = outputFile.Write(finalString.replace(/^(_)/, "") + ",\r\n");
    }
 }
 outputFile.Write("};\r\n");
 inputFile.Close();
 outputFile.Close();
}

Upvotes: 2

Views: 3995

Answers (2)

Nick Louloudakis
Nick Louloudakis

Reputation: 6015

You can use substring in order to remove the last character of the string after you have formed the string:

finalString = finalString.substring(0, finalString.length - 1);

An alternative would be the use of slice, taking into consideration that negative indices are relative to the end of the string:

finalString  = finalString.slice(0,-1);

Take a look in this question for more.

UPDATE: For your case, you could check whether or not you have reached the EOF - meaning you have read the last line, and then apply slice or substring:

//....
var stringReadPosition = readLine.substr(8);
var finalString = stringReadPosition.replace(/\s+/g, ': ');

//Check if stream reached EOF.
if(inputFile.AtEndOfStream) {
    finalString  = finalString.slice(0,-1);
}
asd = outputFile.Write(finalString.replace(/^(_)/, "") + ",\r\n");
//....

Upvotes: 2

Rajani Rampelli
Rajani Rampelli

Reputation: 179

try this asd = asd.replace(/,\s*$/, ""); this will remove last comma, I have tried this, its working .Check if it works in ur code. Try this code inside while loop

Upvotes: 1

Related Questions