简体   繁体   中英

Replace a part of html string using regex in Javascript

In trying to replace parts of a string using a regex.

This is my string

"<p>0</p>
<p>0</p> 
<p>&nbsp;</p>
<p>1</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>2</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>&nbsp;</p>
<p>3</p>"

and im doing this

aboveString.replace('/<p>\&nbsp;<\/p>/g','<br style="clear:both;" />')

I need to replace all instances of the

<p>&nbsp;</p>

to be replaced with

<br style="clear:both;" />

Can you please tell me where am i going wrong?

Your regex '/<p>\\&nbsp;<\\/p>/g' isn't a regex, it's a string. Remove the quotes to make it a regex literal:

aboveString.replace(/<p>\&nbsp;<\/p>/g,'<br style="clear:both;" />')

Demo: http://jsfiddle.net/pTqgX/

I know, its about Regex, but its so obviously doable without Regex:

aboveString.split('<p>&nbsp;</p>').join('<br style="clear:both;" />');

Fiddle

Now downvote me, friends

aboveString.replace(/<p>\&nbsp;<\/p>/g,'<br style="clear:both;" />')

in Javascript u don't write regexp inside "" . Every thing written within "" is treated as String. :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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