[英]Replace HTML closing tags with HTML tags + \n Analysis
I need to replace HTML closing tags with HTML tags + \\n. 我需要用HTML标签+ \\ n替换HTML结束标签。 I've found this SO answer 我找到了这个答案
var regex = new RegExp("(</.*?>)", "gi");
strContent = strContent.replace(regex, "$1 \n ")
.replace(/\/>/g,'/> \n ');
Could someone explain to me what is happening in the above code? 有人可以向我解释上面的代码中发生了什么吗? Why is a regex declared then replaced? 为什么宣布正则表达式被替换? What does each part mean? 每个部分意味着什么?
The first regex (</.*?>)
is searching for all closing tags of the form </span>
or </div>
and selecting the tag as a group. 第一个正则表达式(</.*?>)
正在搜索表单</span>
或</div>
所有结束标记,并选择标记作为一个组。 This group is replaced with the group as found plus a new line. 此组将替换为找到的组以及新行。
The second regex, /\\/>/
is looking for the last two characters of tags that are of the form <img />
or <input />
. 第二个正则表达式, /\\/>/
正在查找<img />
或<input />
形式的标签的最后两个字符。 The \\
is escaping the second /
. \\
正在逃离第二个/
。 Then those two characters are replaced with the same characters plus a new line. 然后用相同的字符和新行替换这两个字符。
It's the regex replace function. 这是正则表达式替换功能。
It can also be written like this: 它也可以这样写:
strContent = strContent.replace(new RegExp("(</.*?>)", "gi"), "$1 \n ").replace(/\/>/g,'/> \n ');
Does that make more sense? 那更有意义吗?
The author decided to declare the Regex object seperately an then referenced it later as input to the Replace method 作者决定单独声明Regex对象,然后将其作为Replace方法的输入引用
I can only speculate, but I guess it was done for debugging reasons. 我只能推测,但我想这是出于调试原因。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.