简体   繁体   English

使用Regex和JavaScript转义括号,方括号和花括号

[英]Escaping parenthesis, brackets and braces with Regex and JavaScript

I have HTML like this example: 我有这样的示例HTML:

<div class="code">
  function something(a, b) 
  {
     return 0;
  }
</div>

I want to surround all parentheses, brackets and braces with a span of class brackets . 我想全部包围括号,括号和大括号与span类的brackets Like this: 像这样:

<div class="code">
  function something<span class="brackets">(a, b<span class="brackets">)</span> 
  <span class="brackets">{</span>
     return 0;
  <span class="brackets">}</span>
</div>

My JavaScript/jQuery so far: 到目前为止,我的JavaScript / jQuery:

$('.code').each(function() {

  $(this).html(
    $(this).html().replace("???", '<span class="brackets">$1</span>')
  );

});

I really don't know what to put in place of ??? 我真的不知道该用什么代替??? . Anything I can find on the internet is people wanting to match between brackets not the actual brackets themselves. 我在互联网上可以找到的是人们想要在方括号之间匹配而不是实际的方括号本身。

Just to be clear I want to replace all instances of ( , ) , { , } , [ and ] . 为了清楚起见,我想替换(){}[]所有实例。

Any help would be hugely appreciated. 任何帮助将不胜感激。

You can just stuff them all into a character class (which matches any single character inside the class). 您可以将它们全部塞入一个字符类(与该类中的任何单个字符匹配)。 The character class itself is denoted by square brackets, so you will have to escape the ones inside (that is only partially true, but it's definitely good practice): 字符类本身用方括号表示,因此您必须在其中将其转义(这只是部分正确,但这绝对是一种好习惯):

/([(){}\[\]])/g

The outer round parentheses are there so that the captured value actually ends up as $1 . 外面有圆括号,因此捕获的值实际上最终为$1 The g is there so that all occurrences are replaced. g在那里,所以所有的出现都被替换了。

Note that this is not a string! 请注意,这不是字符串! Do not surround this with " . Simply supply it as the first argument to replace as it is: 请勿用" 。只需将其作为要replace的第一个参数即可:

...html.replace(/([(){}\[\]])/g, '<span class="brackets">$1</span>')

By the way, you should probably iterate over all text nodes in the DOM and apply the replacement only to those. 顺便说一句,您可能应该遍历DOM中的所有文本节点,并将替换仅应用于这些文本节点。 Otherwise you might add in that tag into attribute values or comments (or worse, embedded JavaScript or CSS). 否则,您可能会将该标签添加到属性值或注释中(或者更糟的是,嵌入的JavaScript或CSS)。

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

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