30

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?

3 Answers 3

85

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, '"');

To account for every variation, per https://symbl.cc/en/unicode-table/#general-punctuation :

var badquotes = 'Replace smart quotes with regular quotes: 2018:’2019:‘201C:”201D:“201A:‚201B:‛ 201E:„201F:‟2032:′2033:″2034:‴2035:‵2036:‶2037:‷';
var goodQuotes = badquotes
  .replace(/[\u2018\u2019\u201a\u201b\u2032\u2035]/g, "'")
  .replace(/[\u201C\u201D\u201E\u201F\u2033\u2034\u2036\u2037]/g, '"');
// Will result in Replace smart quotes with regular quotes: 2018:'2019:'201C:"201D:"201A:'201B:' 201E:"201F:"2032:'2033:"2034:"2035:'2036:"2037:"
Sign up to request clarification or add additional context in comments.

4 Comments

>>> str.replace(/[\u2018\u2019]/g, "#"); Results in: " “I don#t know what you mean by #glory,# ” Alice said."
Right. Why did you put "#" in the replacement string? If you want to replace both sort of quotes, you'd need two calls to .replace(). I'll update the answer.
You can extend this script with the following, which replaces em dashes and ellipses that you get in text boxes when pasting from Word etc: .replace(/[\u2013\u2014]/g, '-') .replace(/[\u2026]/g, '...')
spent three days staring a whole in my laptop trying to figure this out.
6

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.

Comments

1
+50

Combining Pointy and Wooble's answers, if you want to replace the curly quotes with regular quotes:

str = str.replace(/[“”]/g, '"').replace(/[‘’]/g, "'");

So for example:

str = '“I don’t know what you mean by ‘glory,’ ” Alice said.';
str = str.replace(/[“”]/g, '"').replace(/[‘’]/g, "'");
console.log(str)

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.