0

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 ”
4
  • Did you mean for each of those those to be on their own line? Commented Jun 10, 2009 at 1:41
  • 1
    He wants to replace normal quotes with the "curly" ones. Commented Jun 10, 2009 at 1:43
  • OK. I'm going to reformat so it's easier to understand. Commented Jun 10, 2009 at 1:45
  • Does StackOverflow replace smart quotes for posted code? Do you have to use the HTML entities to get them to work? Commented Jun 10, 2009 at 2:03

3 Answers 3

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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?

Comments

0

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;
};

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.