替换 Javascript 字符串中的双引号和单引号

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7760262/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 03:30:16  来源:igfitidea点击:

Replace Both Double and Single Quotes in Javascript String

javascriptreplacespecial-characters

提问by jmease

I am pulling in some information from a database that contains dimensions with both ' and " to denote feet and inches. Those characters being in my string cause me problems later and I need to replace all of the single and double quotes. I can successfully get rid of one or the other by doing:

我正在从一个包含 ' 和 " 尺寸的数据库中提取一些信息来表示英尺和英寸。我的字符串中的这些字符稍后会给我带来问题,我需要替换所有单引号和双引号。我可以成功获得通过执行以下操作来摆脱其中之一:

this.Vals.replace(/\'/g, "")   To get rid of single quotes

or

或者

this.Vals.replace(/\"/g, "")   To get rid of double quotes

How do I get rid of both of these in the same string. I've tried just doing

我如何在同一个字符串中摆脱这两个。我试过只是做

this.Vals.replace(/\"'/g, "")

and

this.Vals.replace(/\"\'/g, "")

But then neither get replaced.

但随后两者都不会被替换。

回答by Joe

You don't escape quotes in regular expressions

您不会在正则表达式中转义引号

this.Vals.replace(/["']/g, "")

回答by Danny

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

回答by Alex Turpin

You don't need to escape it inside. You can use the |character to delimit searches.

你不需要在里面逃脱它。您可以使用该|字符来分隔搜索。

"\"foo\"\'bar\'".replace(/("|')/g, "")

回答by deviousdodo

Try this.Vals.replace(/("|')/g, "")

尝试 this.Vals.replace(/("|')/g, "")