-
Notifications
You must be signed in to change notification settings - Fork 2
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
1 parent
ec66b90
commit a611c8e
Showing
1 changed file
with
24 additions
and
12 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 }; |