arun kamboj
arun kamboj

Reputation: 1315

How to remove white spaces within div using javascript?

I have following html

<div> <div class="first"> First Second </div>  <div class="second">Second</div>  <div class="third">Third</div> <div>

I want this output after removing white spaces.

First SecondSecondThird

i have used this code

    var str = " <div class="first"> First Second </div> <div class="second"> Second</div> <div class="third">Third</div>"; 
   str=  str.replace(/\s+/g, " ").trim();

Any idea how it will work. i need this in pure javascript or anglurjs

Upvotes: 0

Views: 251

Answers (1)

Pranav C Balan
Pranav C Balan

Reputation: 115212

You can use regex /(>)\s+|\s+(<)/g

var str = ' <div class="first"> First Second </div> <div class="second"> Second</div> <div class="third">Third</div>';
str = str.replace(/(>)\s+|\s+(<)/g, "$1$2");
document.write(str)
div {
  display: inline-block
}


Regex explanation here.

Regular expression visualization

Upvotes: 1

Related Questions