Rajeshwar
Rajeshwar

Reputation: 2509

Replace space between html tags only

I have a string like

var x = "<html><head>  <title>Hello!</title> </head> <body> <div class=”div1”> "+
"<h1>This is a headline!</h1> "+
"<br><img src=”header-image.png”>  </div>  "+
"<div class=”div2”>  <a href=”http://www.google.com”> </a>  </div>"+
"<div class='div3'></div>  </body>  </html>";

The output should be

x = "<html><head><title>Hello!</title></head><body><div class=”div1”>"+
"<h1>This is a headline!</h1>"+
"<br><img src=”header-image.png”></div>"+
"<div class=”div2”><a href=”http://www.google.com”></a></div>"+
"<div class='div3'></div></body></html>";

In the output i should not have any spaces between > and < tags only.

If there is any space between element and property, it should be intact. If i have below text

input : <a href='www.google.com'> Click Here </a>  <br/><span>  </span>

output should be

<a href='www.google.com'> Click Here </a><br/><span></span>

Means only the space between closing and opening tags sgould be replaced by empty string "".

I tried

x = x.replace(/>( )</g,"")

and the out put is

"<html><head>  <title>Hello!</title/headbodydiv class=”div1”h1>This is a headline!</h1><br><img src=”header-image.png”>  </div><div class=”div2”>    <a href=”http://www.google.com”></a></div><div class='div3'></div>  </body>  </html>"

I am still getting some spaces in between the tags. Can someone help me on this?

Upvotes: 1

Views: 2711

Answers (3)

Avinash Raj
Avinash Raj

Reputation: 174756

The below regex would replace all the spaces which are present in-between >, < symbols(included) with ><

x.replace(/>\s+</g, "><")

OR

x.replace(/>[ \t]+</g, "><")

Use trim() function to remove all leading and trailing spaces.

> s.replace(/>\s+</g, "><").trim()
'<a href=\'www.google.com\'> Click Here </a><br/><span></span>'

Example:

> var s = "<a href='www.google.com'> Click Here </a>  <br/><span>  </span>"
undefined
> s.replace(/>\s+</g, "><")
'<a href=\'www.google.com\'> Click Here </a><br/><span></span>'

Upvotes: 0

vks
vks

Reputation: 67978

Simply apply this regex and replace by empty string.

(?<=>)\s*

See demo.

https://www.regex101.com/r/rK5lU1/35

Edit:

Seems like lookbehin dis not supported.use

>\s*

and replace by >.

Upvotes: 1

alpha bravo
alpha bravo

Reputation: 7948

or use this pattern

(?<=>) +(?=<)

Demo

Upvotes: 0

Related Questions