Javascript正则表达式可删除不必要的< br>& nbsp; [英] Javascript Regular expression to remove unwanted <br>,  

查看:169
本文介绍了Javascript正则表达式可删除不必要的< br>& nbsp;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的JS搅动
&lt;div id="grouplogo_nav"&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;ul&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;li&gt;&lt;a class="group_hlfppt" target="_blank" href="http://www.hlfppt.org/"&gt;&amp;nbsp;&lt;/a&gt;&lt;/li&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/ul&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/div&gt;

I have a JS stirng like this
&lt;div id="grouplogo_nav"&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;ul&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;li&gt;&lt;a class="group_hlfppt" target="_blank" href="http://www.hlfppt.org/"&gt;&amp;nbsp;&lt;/a&gt;&lt;/li&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/ul&gt;<br>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &lt;/div&gt;

我需要删除仅在&gt;&lt;之间的所有<br>$nbsp;.我试图写一个正则表达式,但是没有正确.有人有解决方案吗?

I need to remove all <br> and $nbsp; that are only between &gt; and &lt;. I tried to write a regular expression, but didn't got it right. Does anybody have a solution.

请注意,我只想删除标签b/w &gt;&lt;

Please note i want to remove only the tags b/w &gt; and &lt;

推荐答案

s.replace(/(&gt;)(?:&nbsp;|<br>)+(\s?&lt;)/g,'$1$2');

请勿在生产中使用此功能.参见Phil H的回答.

Don't use this in production. See the answer from Phil H.

我尝试解释一下,希望我的英语足够.

I try to explain it a bit and hope my english is good enough.

基本上,我们在这里有两种不同的括号.第一对和第三对()是普通括号.它们用于记住与封闭模式匹配的字符,并将字符分组在一起.对于第二对,我们不需要记住字符以备后用,因此我们通过使用(?:)格式禁用记住"功能,而仅对字符进行分组以使+正常工作. +量词表示一次或多次出现",因此&nbsp;<br>必须存在一次或多次.最后一部分(\s?&lt;)与一个空格字符(\s)匹配,该字符可能丢失或一次出现(?),后跟字符&lt;. $1$2是一种变量,将其替换为记住的第一和第三括号中的字符.

Basically we have two different kinds of parentheses here. The first pair and third pair () are normal parentheses. They are used to remember the characters that are matched by the enclosed pattern and group the characters together. For the second pair, we don't need to remember the characters for later use, so we disable the "remember" functionality by using the form (?:) and only group the characters to make the + work as expected. The + quantifier means "one or more occurrences", so &nbsp; or <br> must be there one or more times. The last part (\s?&lt;) matches a whitespace character (\s), which can be missing or occur one time (?), followed by the characters &lt;. $1 and $2 are kind of variables that are replaces by the remembered characters of the first and third parentheses.

MDN提供了一个漂亮的表格,其中解释了所有特殊字符.

MDN provides a nice table, which explains all the special characters.

这篇关于Javascript正则表达式可删除不必要的&lt; br&gt;&amp; nbsp;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆