如何使用javascript删除div中的空格?

时间:2016-05-28 06:03:26

标签: javascript angularjs

我有以下html

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

删除空格后我想要这个输出。

First SecondSecondThird

我使用过此代码

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

知道它将如何运作。我需要这个纯粹的javascript或anglurjs

1 个答案:

答案 0 :(得分:1)

您可以使用正则表达式/(>)\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