Search code examples
javascriptquotesquotation-marks

replace symbol in javascript


Does anyone know how can I replace this 2 symbol below from the string into code?

  • ' left single quotation mark into ‘
  • ' right single quotation mark into ’
  • " left double quotation mark into “
  • " right double quotation mark into ”

Solution

  • Knowing which way to make the quotes go (left or right) won't be easy if you want it to be foolproof. If it's not that important to make it exactly right all the time, you could use a couple of regexes:

    function curlyQuotes(inp) {
        return inp.replace(/(\b)'/, "$1’")
                  .replace(/'(\b)/, "‘$1")
                  .replace(/(\b)"/, "$1”")
                  .replace(/"(\b)/, "“$1")
    }
    
    curlyQuotes("'He said that he was \"busy\"', said O'reilly")
    // ‘He said that he was “busy”', said O’reilly
    

    You'll see that the second ' doesn't change properly.