javascript 从字符串中删除所有 <br>

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4184272/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 10:37:14  来源:igfitidea点击:

remove all <br> from a string

javascriptregex

提问by user357034

I have a string that i would like to remove all occurrences of <br>

我有一个字符串,我想删除所有出现的 <br>

I tried this and it did not work.

我试过这个,但没有用。

    productName = productName.replace("<br>"," ");

However this worked but only for the first <br>

然而,这有效但仅适用于第一个 <br>

    productName = productName.replace("&lt;br&gt;"," ");

How would I get it to work for all <br>in the string.

我将如何让它对<br>字符串中的所有人都起作用。

Edit: this is the string...

编辑:这是字符串...

00-6189 Start Mech Switch&lt;br&gt;00-6189 Start Mech Switch&lt;br&gt;00-6189 Start Mech Switch&lt;br&gt;

00-6189 Start Mech Switch&lt;br&gt;00-6189 Start Mech Switch&lt;br&gt;00-6189 Start Mech Switch&lt;br&gt;

My apologies for being a little misleading with the <br>as it should have been &lt;br&gt;

我很抱歉,<br>因为它应该有一点误导&lt;br&gt;

回答by Gabriele Petrioli

Looks like your string is encoded so use

看起来您的字符串已编码,因此请使用

productName = productName.replace(/&lt;br&gt;/g," ");

note the gafter the regular expression which means globally, to match all occurrences.

注意g正则表达式后面的意思是全局匹配所有出现的。

demo at http://www.jsfiddle.net/gaby/VDxHx/

演示在http://www.jsfiddle.net/gaby/VDxHx/

回答by DavideDM

Using regular expression you can use this pattern

使用正则表达式,您可以使用此模式

/(<|&lt;)br\s*\/*(>|&gt;)/g
productName = productName.replace(/(<|&lt;)br\s*\/*(>|&gt;)/g,' ');

That pattern matches

该模式匹配

 <br>, <br />,<br/>,<br     />,<br  >,
 or &lt;br&gt;, &lt;br/&gt;, &lt;br /&gt;

etc...

等等...

回答by Darin Dimitrov

You could use the gflag in your regular expression. This indicates that the replace will be performed globally on all occurrences and not only on the first one.

您可以g在正则表达式中使用该标志。这表明替换将在所有事件上全局执行,而不仅仅是在第一个。

productName = productName.replace(/\<br\>/g," ");

Of course you should be aware that this won't replace <br/>nor <br />but only <br>.

当然,您应该知道这不会取代<br/>也不会<br />仅取代<br>.

See an exampleof this working on ideone.

看到一个例子这个工作对ideone的。



UPDATE:

更新:

Now that you've provided an example with your input here's a working regex you might use to replace:

既然您已经提供了输入示例,这里是您可以用来替换的有效正则表达式:

productName = productName.replace(/&lt;br&gt;/g, ' ');

回答by m4rc

I've not tested it but you could try something like this

我没有测试过,但你可以试试这样的

productName.replace(/\<br\>/g,' ');