Converting ″Straight Quotes″ to “Curly Quotes”

后端 未结 7 1076
旧时难觅i
旧时难觅i 2020-12-13 19:53

I have an application which uses a Javascript-based rules engine. I need a way to convert regular straight quotes into curly (or smart) quotes. It’d be easy to just do a <

7条回答
  •  南方客
    南方客 (楼主)
    2020-12-13 20:29

    You could replace all that preceed a word character with the left quote, and all that follow a word character with a right quote.

    str = str.replace(/"(?=\w|$)/g, "“");
    str = str.replace(/(?<=\w|^)"/g, "”"); // IF the language supports look-
                                                 // behind. Otherwise, see below.
    

    As pointed out in the comments below, this doesn't take punctuation into account, but easily can:

    /(?<=[\w,.?!\)]|^)"/g
    

    [Edit:] For languages that don't support look-behind, like Javascript, as long as you replace all the front-facing ones first, you have two options:

    str = str.replace(/"/g, "”"); // Replace the rest with right curly quotes
    // or...
    str = str.replace(/\b"/g, "”"); // Replace any quotes after a word
                                          // boundary with right curly quotes
    

    (I've left the original solution above in case this is helpful to someone using a language that does support look-behind)

提交回复
热议问题