Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I am trying to replace curly quotes:

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

Using:

str.replace(/['"]/g,'');

Why it does not work? How can I do this?

like image 646
dokondr Avatar asked Feb 22 '12 19:02

dokondr


People also ask

How do you replace a quote in JavaScript?

Use the String. replace() method to replace single with double quotes, e.g. const replaced = str. replace(/'/g, " ); . The replace method will return a new string where all occurrences of single quotes are replaced with double quotes.


2 Answers

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, '"');
like image 191
Pointy Avatar answered Oct 08 '22 16:10

Pointy


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.

like image 24
Wooble Avatar answered Oct 08 '22 17:10

Wooble