简体   繁体   English

jQuery - 替换字符串中的所有括号

[英]jQuery - Replace all parentheses in a string

I tried this: 我试过这个:

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

It works for all double and single quotes but for parentheses, this only replaces the first parenthesis in the string. 它适用于所有双引号和单引号,但对于括号,这只替换字符串中的第一个括号。

How can I make it work to replace all parentheses in the string using JavaScript? 如何使用JavaScript替换字符串中的所有括号? Or replace all special characters in a string? 或者替换字符串中的所有特殊字符?

Try the following: 请尝试以下方法:

mystring= mystring.replace(/"/g, "").replace(/'/g, "").replace(/\(|\)/g, "");

A little bit of REGEX to grab those pesky parentheses. 一点点REGEX来抓住那些讨厌的括号。

You should use something more like this: 你应该使用更像这样的东西:

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

The reason it wasn't working for the others is because you forgot the "global" argument (g) 它不适合其他人的原因是因为你忘记了“全球”论点(g)

note that [...] is a character class. 请注意[...]是一个字符类。 anything between those brackets is replaced. 这些括号之间的任何内容都被替

You should be able to do this in a single replace statement. 您应该能够在单个替换语句中执行此操作。

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

If you're trying to replace all special characters you might want to use a pattern like this. 如果您尝试替换所有特殊字符,则可能需要使用此类模式。

mystring = mystring.replace(/\W/g, "");

Which will replace any non-word character. 这将取代任何非单词字符。

You can also use a regular experession if you're looking for parenthesis, you just need to escape them. 如果你正在寻找括号,你也可以使用常规训练,你只需要逃避它们。

mystring = mystring.replace(/\(|\)/g, '');

This will remove all ( and ) in the entire string. 这将删除整个字符串中的所有()

只需一个替换就可以:

"\"a(b)c'd{e}f[g]".replace(/[\(\)\[\]{}'"]/g,"")

这可以解决问题: myString = myString.replace(/\\"|\\'|\\(|\\)/) 示例

这应该工作:

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

That's because to replace multiple occurrences you must use a regex as the search string where you are using a string literal. 这是因为要替换多次出现,您必须使用正则表达式作为您使用字符串文字的搜索字符串。 As you have found searching by strings will only replace the first occurrence. 您发现按字符串搜索只会替换第一次出现。

The string-based replace method will not replace globally. 基于字符串的替换方法不会全局替换。 As such, you probably want to use the regex-based replacing method. 因此,您可能希望使用基于正则表达式的替换方法。 It should be noted: 应该指出:

You need to escape ( and ) as they are used for group matching: 您需要转义()因为它们用于组匹配:

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

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

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