在Javascript中从字符串中删除括号 [英] Remove Parenthesis from String in Javascript
问题描述
x = x.replace(/[{()}]/g, '');
y = y.replace(/[{()}]/g, '');
x = x.replace(/[\[\]']+/g, '');
y = y.replace(/[\[\]']+/g, '');
好吧我明白第一个块删除了大括号,第二个代码块删除了常规括号。我想现在删除括号..有人可以告诉我怎么样?
okay I understand that the first block removes the curly brackets, and the second block of code removes the regular brackets. I want to remove parenthesis now.. can someone show me how?
我通过谷歌搜索获得了上述代码..但我不明白如何他们想出了这个,有人可以解释一下吗?谢谢
I've gotten the above code by just googling.. but I don't understand "how" they come up with this, can someone please explain? thanks
推荐答案
First Regex
First Regex
x = x.replace(/[{()}]/g, '');
y = y.replace(/[{()}]/g, '');
在你的第一个正则表达式 / [{()}] / g
外方括号 []
生成字符类,它将匹配其中指定的字符之一。在这种情况下,字符 {
(
)
}
。
In your first regex /[{()}]/g
the outer square brackets []
makes a character class, it will match one of the character specified inside of it. In this case the characters {
(
)
}
.
在 / regexp /
之外你有 g
(全局)修饰符意味着您的整个正则表达式将尽可能多地匹配,并且它不会只对第一个匹配进行。
Outside of the /regexp/
you have the g
(global) modifier meaning that your entire regular expression will match as many times as it can , and it will not just make to the first match.
x = x.replace(/[\[\]']+/g, '');
y = y.replace(/[\[\]']+/g, '');
在你的第二个正则表达式 / [\ [\]'] + / g
外方括号 []
生成字符类,它将匹配其中一个指定的字符它。在这种情况下,字符 [
]
'
。
In your second regex /[\[\]']+/g
the outer square brackets []
makes a character class, it will match one of the character specified inside of it. In this case the characters [
]
'
.
请注意,方括号显示为 [字符类] 内的 \ [
\]
。
Note that the square brackets appear scaped inside the [character class] as \[
\]
.
之后你指定了 +
量词,它使前面的规则连续匹配一个或多个
次。请注意,这是多余的,即使它有效,这也不是你想要的。
After it you have specified a +
quantifier, it makes the preceding rule match one or more
times in a row. Note that this is redundant, even if it works, this is not quite what you want.
/ regularexpression / $ c之外$ c>你有
g
(全局)修饰符,这意味着你的整个正则表达式将尽可能多地匹配,并且它不会只需进行第一场比赛。
Outside of the /regularexpression/
you have the g
(global) modifier meaning that your entire regular expression will match as many times as it can , and it will not just make to the first match.
建议的解决方案
run1.onclick = function() {
//removes "(" and ")"
output1.innerHTML = input1.value.replace(/[()]/g, '');
}
run2.onclick = function() {
//removes (){}[]
output2.innerHTML = input2.value.replace(/[\])}[{(]/g, '');
}
<p>Remove ()</p>
<input id="input1" type="text" value="(123) 1234-1234">
<input id="run1" type="button" value="run">
<span id="output1"></span>
<hr>
<p>Remove ()[]{}</p>
<input id="input2" type="text" value="Hello (this) is [] a {{test}}!">
<input id="run2" type="button" value="run">
<span id="output2"></span>
这篇关于在Javascript中从字符串中删除括号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!