Created
May 29, 2025 20:04
-
-
Save smcllns/d72e91cad4ca41c064000623d4975d99 to your computer and use it in GitHub Desktop.
# Replacing straight quotes with curly quotes (smart quotes)
This file contains hidden or 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
| // Replace straight quotes with curly quotes | |
| // Put inside a <script> tag on your html page | |
| (() => { | |
| const curly = (s) => | |
| s | |
| .replace(/(^|[\s([{])"(?=\S)/g, "$1“") // opening double | |
| .replace(/"/g, "”") // closing double | |
| .replace(/(^|[\s([{])'(?=\S)/g, "$1‘") // opening single | |
| .replace(/'/g, "’"); // closing single | |
| const curlyAllTextNodes = (node) => { | |
| if (node.nodeType === Node.TEXT_NODE) { | |
| node.nodeValue = curly(node.nodeValue); | |
| } else if (node.nodeType === Node.ELEMENT_NODE && !/(script|style|code|pre)/i.test(node.tagName)) { | |
| for (let child of node.childNodes) curlyAllTextNodes(child); | |
| } | |
| }; | |
| curlyAllTextNodes(document.body); | |
| })(); |
This file contains hidden or 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
| <!DOCTYPE html> | |
| <head> | |
| <title>Example Usage</title> | |
| </head> | |
| <body> | |
| <h1>Hello World. It's good to see you again.</h1> | |
| <div class="subtitle"> | |
| <p>He said, "She's my best friend."</p> | |
| </div> | |
| <pre> | |
| <code> | |
| function exampleFunction() { | |
| console.log("These quotes will not be updated to curly quotes since it's inside a code block."); | |
| } | |
| </code> | |
| </pre> | |
| <script> | |
| (() => { | |
| const curly = (s) => | |
| s | |
| .replace(/(^|[\s([{])"(?=\S)/g, "$1“") // opening double | |
| .replace(/"/g, "”") // closing double | |
| .replace(/(^|[\s([{])'(?=\S)/g, "$1‘") // opening single | |
| .replace(/'/g, "’"); // closing single | |
| const curlyAllTextNodes = (node) => { | |
| if (node.nodeType === Node.TEXT_NODE) { | |
| node.nodeValue = curly(node.nodeValue); | |
| } else if (node.nodeType === Node.ELEMENT_NODE && !/(script|style|code|pre)/i.test(node.tagName)) { | |
| for (let child of node.childNodes) curlyAllTextNodes(child); | |
| } | |
| }; | |
| curlyAllTextNodes(document.body); | |
| })(); | |
| </script> | |
| </body> | |
| </html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment