Skip to content

Commit

Permalink
🤞
Browse files Browse the repository at this point in the history
  • Loading branch information
tomlovesgithub committed Nov 27, 2024
1 parent ec66b90 commit a611c8e
Showing 1 changed file with 24 additions and 12 deletions.
36 changes: 24 additions & 12 deletions src/helpers/csv.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,34 @@
/**
* This function is used when converting arrays into csv strings
* This function is used when converting arrays into CSV strings.
* It does the following:
* - Converts the value to a string using String(value)
* - If the value contains a comma (,), double quotes ("), or other special characters, it wraps the value in double quotes
* - If the value already contains double quotes, those quotes are escaped by replacing each " with ""
* @param {*} value
* @returns
* - Converts the value to a string using String(value).
* - If the value starts with `=`, it prepends a single quote (`'`) to prevent formula interpretation in Excel.
* - If the value contains any of the following special characters: comma (,), double quote ("), colon (:), semicolon (;), newline (\n), plus (+), minus (-), or at (@), it wraps the value in double quotes.
* - If the value already contains double quotes, those quotes are escaped by replacing each " with "".
*
* @param {*} value - The value to be escaped.
* @returns {string} - The escaped value suitable for CSV format.
*/
const escapeValue = (value) => {
// Convert the value to a string and wrap in quotes if it contains commas or quotes
const stringValue = String(value);
if (stringValue.includes(',') || stringValue.includes('"')) {
// Convert the value to a string
let stringValue = String(value);

// Prevent Excel from interpreting values starting with "=" as formulas
if (stringValue.startsWith('=')) {
stringValue = `'${stringValue}`;
}

// Check for special characters (comma, quote, colon, semicolon, newline, plus, minus, @)
if (stringValue.includes(',') || stringValue.includes('"') || stringValue.includes(':') ||
stringValue.includes(';') || stringValue.includes('\n') || stringValue.includes('+') ||
stringValue.includes('-') || stringValue.includes('@')) {

// Escape internal double quotes and wrap the value in quotes
return `"${stringValue.replace(/"/g, '""')}"`;
}

// Return the value as is if no special characters are found
return stringValue;
};

export {
escapeValue
};
export { escapeValue };

0 comments on commit a611c8e

Please sign in to comment.