简体   繁体   English

如何使用 Javascript 替换字符串中的大引号?

[英]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?我怎样才能做到这一点?

You might have to (or prefer to) use Unicode escapes:您可能必须(或更喜欢)使用 Unicode 转义:

var goodQuotes = badQuotes.replace(/[\u2018\u2019]/g, "'");

That's for funny single quotes;那是有趣的单引号; the codes for double quotes are 201C and 201D.双引号的代码是 201C 和 201D。

edit — thus to completely replace all the fancy quotes:编辑- 从而完全替换所有花哨的引号:

var goodQuotes = badQuotes
  .replace(/[\u2018\u2019]/g, "'")
  .replace(/[\u201C\u201D]/g, '"');

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.它不起作用,因为您试图用空字符串替换 ASCII 撇号(或单引号)和引号字符,而实际上源字符串中的内容不是 ASCII 字符。

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

works.作品。

Combining Pointy and Wooble's answers, if you want to replace the curly quotes with regular quotes:结合PointyWooble 的答案,如果您想用常规引号替换大引号:

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)

I know this is an old question. 我知道这是一个老问题。 Just want to add something. 只想添加一些东西。 The quotes you are trying to replace are called "Smart Quotes". 您要替换的引号称为“智能引号”。

The below function covers most of them 以下功能涵盖了大部分功能

public static String replaceSmartQuotes(String str) {
    String retVal = str;
    retVal = retVal.replaceAll( "[\u2018\u2019\u201A\u201B\u2032\u2035]", "'" );
    retVal = retVal.replaceAll("[\u201C\u201D\u201E\u201F\u2033\u2036]","\"");
    return retVal;
}

Hope this helps someone. 希望这有助于某人。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM