-
Notifications
You must be signed in to change notification settings - Fork 7
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add swap quotes command and update test case names.
- Loading branch information
1 parent
4c171e4
commit 0af3069
Showing
2 changed files
with
93 additions
and
40 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 |
---|---|---|
@@ -0,0 +1,52 @@ | ||
export const swapQuotes = (str: string): string => { | ||
const singleQuote = "'"; | ||
const doubleQuote = '"'; | ||
|
||
// Check if the string is at least two characters and starts and ends with the same quote | ||
if (str.length < 2) { | ||
return str; // Return as is if not properly quoted | ||
} | ||
|
||
const firstChar = str[0]; | ||
const lastChar = str[str.length - 1]; | ||
|
||
if ( | ||
(firstChar !== singleQuote && firstChar !== doubleQuote) || | ||
firstChar !== lastChar | ||
) { | ||
// Not properly quoted, return as is | ||
return str; | ||
} | ||
|
||
const originalQuote = firstChar; | ||
const newQuote = originalQuote === singleQuote ? doubleQuote : singleQuote; | ||
let content = str.slice(1, -1); | ||
|
||
// Swap inner quotes | ||
content = content.replace(/['"]/g, (match, offset) => { | ||
// Determine if the quote is part of an apostrophe | ||
const prevChar = content[offset - 1]; | ||
const nextChar = content[offset + 1]; | ||
const isApostrophe = | ||
match === "'" && | ||
/[a-zA-Z]/.test(prevChar || "") && | ||
/[a-zA-Z]/.test(nextChar || ""); | ||
|
||
if (isApostrophe) { | ||
// Handle apostrophe based on the desired output | ||
if (newQuote === singleQuote) { | ||
// Escape apostrophe when outer quote is single quote | ||
return "\\'"; | ||
} else { | ||
// Keep apostrophe as is when outer quote is double quote | ||
return match; | ||
} | ||
} else { | ||
// Swap the quote | ||
return match === originalQuote ? newQuote : originalQuote; | ||
} | ||
}); | ||
|
||
// Return the new string with swapped quotes | ||
return newQuote + content + newQuote; | ||
}; |
Oops, something went wrong.