Alex Alex - 1 year ago 70
Javascript Question

Dumb quotes into smart quotes Javascript issue

I have some JavaScript code that transforms dumb quotes into smart quotes in a


The problem appears when you add dumb quotes at the beginning of the line they only close. For example you get this:

”dumb quotes” instead of “dumb quotes”

Try out the demo:

The code I’m using:

function replace(a) {
a = a.replace(/(^|[-\u2014\s(\["])'/g, "$1\u2018"); // opening singles
a = a.replace(/'/g, "\u2019"); // closing singles & apostrophes
a = a.replace(/(^|[-\u2014/\[(\u2018\s])"/g, "$1\u201c"); // opening doubles
a = a.replace(/"/g, "\u201d"); // closing doubles
a = a.replace(/--/g, "\u2014"); // em-dashes
return a };

Any ideas? Thanks!

P.S. I suck at regular expressions…

Answer Source

Try this:

var a = '"dumb quotes" instead -- of "dumb quotes", fixed it\'s';

 a = a.replace(/'\b/g, "\u2018")     // Opening singles
      .replace(/\b'/g, "\u2019")     // Closing singles
      .replace(/"\b/g, "\u201c")     // Opening doubles
      .replace(/\b"/g, "\u201d")     // Closing doubles
      .replace(/--/g,  "\u2014")     // em-dashes
      .replace(/\b\u2018\b/g,  "'"); // And things like "it's" back to normal.
// Note the missing `;` in these lines. I'm chaining the `.replace()` functions.  


'“dumb quotes” instead — of “dumb quotes”, fixed it's'

Basically, you were looking for the word boundary: \b

Here's an updated fiddle

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download