views:

697

answers:

3

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 ”
+1  A: 

The hard part is identifying apostrophes, which will mess up the count of single-quotes.

For the double-quotes, I think it's safe to find them all and replace the odd ones with the left curly and the even ones with the right curly. Unless you have a case with nested quotations.

What is the source? English text? Code?

Nosredna
+1  A: 

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.

nickf
A: 

I recently wrote a typography prettification engine called jsPrettify that does just that. Here's a quotes-only version the algorithm I use (original here):

prettifyStr = function(text) {
  var e = {
    lsquo:  '\u2018',
    rsquo:  '\u2019',
    ldquo:  '\u201c',
    rdquo:  '\u201d',
  };
  var subs = [
    {pattern: "(^|[\\s\"])'",      replace: '$1' + e.lsquo},
    {pattern: '(^|[\\s-])"',       replace: '$1' + e.ldquo},
    {pattern: "'($|[\\s\"])?",     replace: e.rsquo + '$1'},
    {pattern: '"($|[\\s.,;:?!])',  replace: e.rdquo + '$1'}
  ];
  for (var i = 0; i < subs.length; i++) {
    var sub = subs[i];
    var pattern = new RegExp(sub.pattern, 'g');
    text = text.replace(pattern, sub.replace);
  };
  return text;
};
Steven Dee