|
| 1 | +export const swapQuotes = (str: string): string => { |
| 2 | + const singleQuote = "'"; |
| 3 | + const doubleQuote = '"'; |
| 4 | + |
| 5 | + // Check if the string is at least two characters and starts and ends with the same quote |
| 6 | + if (str.length < 2) { |
| 7 | + return str; // Return as is if not properly quoted |
| 8 | + } |
| 9 | + |
| 10 | + const firstChar = str[0]; |
| 11 | + const lastChar = str[str.length - 1]; |
| 12 | + |
| 13 | + if ( |
| 14 | + (firstChar !== singleQuote && firstChar !== doubleQuote) || |
| 15 | + firstChar !== lastChar |
| 16 | + ) { |
| 17 | + // Not properly quoted, return as is |
| 18 | + return str; |
| 19 | + } |
| 20 | + |
| 21 | + const originalQuote = firstChar; |
| 22 | + const newQuote = originalQuote === singleQuote ? doubleQuote : singleQuote; |
| 23 | + let content = str.slice(1, -1); |
| 24 | + |
| 25 | + // Swap inner quotes |
| 26 | + content = content.replace(/['"]/g, (match, offset) => { |
| 27 | + // Determine if the quote is part of an apostrophe |
| 28 | + const prevChar = content[offset - 1]; |
| 29 | + const nextChar = content[offset + 1]; |
| 30 | + const isApostrophe = |
| 31 | + match === "'" && |
| 32 | + /[a-zA-Z]/.test(prevChar || "") && |
| 33 | + /[a-zA-Z]/.test(nextChar || ""); |
| 34 | + |
| 35 | + if (isApostrophe) { |
| 36 | + // Handle apostrophe based on the desired output |
| 37 | + if (newQuote === singleQuote) { |
| 38 | + // Escape apostrophe when outer quote is single quote |
| 39 | + return "\\'"; |
| 40 | + } else { |
| 41 | + // Keep apostrophe as is when outer quote is double quote |
| 42 | + return match; |
| 43 | + } |
| 44 | + } else { |
| 45 | + // Swap the quote |
| 46 | + return match === originalQuote ? newQuote : originalQuote; |
| 47 | + } |
| 48 | + }); |
| 49 | + |
| 50 | + // Return the new string with swapped quotes |
| 51 | + return newQuote + content + newQuote; |
| 52 | +}; |
0 commit comments