最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

regex - triming <br> tag in javascript using regular expressions - Stack Overflow

programmeradmin3浏览0评论

I have a regex that I wanted to trim the <br> of a variable

str1.replace(/^&lt;br&gt;|&lt;br&gt;$/g,'');

example i want to trim a string something like this

var str1 = "<br>hooray!<br>";

and i want it to be like this

var str = "hooray!";

but it seems not to be working...

what is the correct regex for removing the first and last <br> tag?

I have a regex that I wanted to trim the <br> of a variable

str1.replace(/^&lt;br&gt;|&lt;br&gt;$/g,'');

example i want to trim a string something like this

var str1 = "<br>hooray!<br>";

and i want it to be like this

var str = "hooray!";

but it seems not to be working...

what is the correct regex for removing the first and last <br> tag?

Share Improve this question edited Apr 24, 2012 at 10:25 Netorica asked Apr 24, 2012 at 10:20 NetoricaNetorica 19.4k19 gold badges77 silver badges109 bronze badges 3
  • Please give some sample input strings and expected output for corresponding input string – Shekhar Commented Apr 24, 2012 at 10:21
  • 1 Assuming you've already tried /^<br>|<br>$/g? – Josh Davenport-Smith Commented Apr 24, 2012 at 10:22
  • yes i tried it... it doesn't work... – Netorica Commented Apr 24, 2012 at 10:24
Add a ment  | 

5 Answers 5

Reset to default 6

Try this regex:

str1.replace(/(^<br>|<br>$)/g,"");

Demo on this fiddle

Try this:

var mystring = '<br>hooray!<br>';
var find = "<br>"; 
var regex = new RegExp(find, "g"); 
var result = mystring.replace(regex, "");

Here is the fiddle

I think br tag is usually written as <br/> so you can use regex like <br[ ]?/>;

If you want to cover br tag which is written as <br> </br>then you have to use <br>[\s\S]*?<br[ ]?/>

After question is edited

for input like <br>hooray!<br> this, you can use just <br> and replace all matches with blank

Try this:
(?im)(^<br[\s/]*>|<br[\s/]*>$)

JavaScript Code:

result = subject.replace(/(?:(?:^<br[\s\/]*>)|(?:<br[\s\/]*>$))/mg, "");

This appeared to work for me and handle cases where the break tag was strangely encoded...

var newData = data.replace(/&lt;br ?\/\>|&lt;br ?\/&rt;|\<br ?\/\>/g, "\n");
发布评论

评论列表(0)

  1. 暂无评论