简体   繁体   English

如何在javascript中组合正则表达式?

[英]How to combine regular expressions in javascript?

This might be easy for those who play with regular expressions. 对于那些使用正则表达式的人来说,这可能很容易。

str = "Here is 'sample' test";
str = str .replace(new RegExp('"', 'g'), '');
str = str .replace(new RegExp("'", 'g'), '');

How to combine 2nd and 3rd line, I want to combine regular expressions new RegExp('"', 'g') and new RegExp("'", 'g') into one regular expression, this will make it in one line. Thanks in advance. 如何组合第2行和第3行,我想将正则表达式new RegExp('"', 'g')new RegExp("'", 'g')成一个正则表达式,这将使它在一行中。提前致谢。

str = str.replace(/"|'/g, '')
str.replace(/['"]+/g, '')

尝试:

str = str.replace(new RegExp('["\']', 'g'), '');

You can simply use a character class for this, to match both single and double quotes you can use ['"] . 你可以简单地使用一个字符类来匹配你可以使用['"]单引号和双引号。

In a full regex you would need to escape one of the quotes though. 在一个完整的正则表达式,你需要逃脱其中一个引号。

var str = "here is 'sample' test";
str = str.replace(/["']/g, '');

Similar to Andrew's solution : Andrew的解决方案类似:

str.replace(/"|'/, 'g')

And if you seeking for a good explanation then this has been discussed on a different threat where Alan Moore explains good. 如果你寻求一个好的解释,那么就已经讨论过艾伦摩尔解释良好的另一个威胁。 Read here . 在这里阅读

str = "Here is 'sample' test".replace(new RegExp('"', 'g'), '').replace(new RegExp("'", 'g'), '');

一个与你的基本相同的例子,除了它使用方法链。

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

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