How to replace curly quotation marks in a string using Javascript?

前端 未结 3 458
挽巷
挽巷 2020-12-05 07:02

I am trying to replace curly quotes:

str = \'“I don’t know what you mean by ‘glory,’ ” Alice said.\';

Using:

str.replace(/[         


        
相关标签:
3条回答
  • 2020-12-05 07:50

    It doesn't work because you're trying to replace the ASCII apostrophe (or single-quote) and quote characters with the empty string, when what's actually in your source string aren't ASCII characters.

    str.replace(/[“”‘’]/g,'');
    

    works.

    0 讨论(0)
  • 2020-12-05 07:55

    You might have to (or prefer to) use Unicode escapes:

    var goodQuotes = badQuotes.replace(/[\u2018\u2019]/g, "'");
    

    That's for funny single quotes; the codes for double quotes are 201C and 201D.

    edit — thus to completely replace all the fancy quotes:

    var goodQuotes = badQuotes
      .replace(/[\u2018\u2019]/g, "'")
      .replace(/[\u201C\u201D]/g, '"');
    
    0 讨论(0)
  • 2020-12-05 08:07

    There is now a library called 'SmartQuotes' that will correctly do the job of replacing standard coder's quotes/apostrophes with pretty, typographer's smart quotes -- better than using a simpler search-and-replace as it gets the opening/closing correct.

    0 讨论(0)
提交回复
热议问题