Encountering a CSV File with an Unusual First Line
I came across a CSV file like the one below. (This is not actual business data.)
hogehoge
name,value,count
りんご,100,2
バナナ,150,4
In this scenario, there's an unwanted string in the first line that isn't in CSV format. I needed to remove it before processing the CSV data. Let's assume the line breaks are LF.
Removing Only the First Line of a Multi-Line String
Surprisingly, I couldn't find many articles on this topic, so I'm documenting it before I forget.
This can be achieved with a combination of indexOf and substr.
// Define a multi-line string (In reality, this would be read from a file)
const inputString = `hogehoge
name,value,count
りんご,100,2
バナナ,150,4`;
// Find the position of the first line break
const firstRowEndPos = inputString.indexOf('\n', 0);
// Extract the string starting from the position after the first line break
const outputString = inputString.substr(firstRowEndPos + 1);
// Display the result
console.log(outputString);
In Conclusion
It was relatively simple to implement. If you also need to consider CR, it might become a bit more complex.
Top comments (0)