如何使用javascript或jquery删除多余的空格?

Amr*_*rhy 26 html javascript jquery

我得到HTML元素包含这个:

  <!--Product Style-->  <div style="float: right; padding-top: 4px; padding-bottom: 5px;">  P6C245RO </div>  <div style="text-transform: uppercase; font-weight: bold; padding-top: 4px; padding-bottom: 5px;">  Style </div>  <div style="clear: both; border-top: 1px solid rgb(216, 216, 216); padding-top: 4px;">  <!--Product Description-->  <div style="font-size: 11px ! important;"></div>  <div style="background: url(&quot;http://ii.armaniexchange.com/ArmaniExchange/images/en_US/global/globalgraphics/bullet.gif&quot;) no-repeat scroll 0pt 4px transparent; padding-left: 12px;">fine tonal striped fabric</div>  <div style="background: url(&quot;http://ii.armaniexchange.com/ArmaniExchange/images/en_US/global/globalgraphics/bullet.gif&quot;) no-repeat scroll 0pt 4px transparent; padding-left: 12px;">epaulettes and sleeve tab</div>  <div style="background: url(&quot;http://ii.armaniexchange.com/ArmaniExchange/images/en_US/global/globalgraphics/bullet.gif&quot;) no-repeat scroll 0pt 4px transparent; padding-left: 12px;">metal logo plate on the chest pocket</div>  
Run Code Online (Sandbox Code Playgroud)

当我使用jquery读取它时,我会.text()在文本之间包含很多空格和/ n但没有html标记.

如何删除所有这些空格并使用jquery或纯javascript返回干净的文本?

Mat*_*t S 60

element.text().replace(/\s+/g, " ");
Run Code Online (Sandbox Code Playgroud)

这使用正则表达式(/.../)在整个元素的文本中搜索一个或多个(+)空白字符(\s)(g全局修饰符,它找到所有匹配而不是在第一次匹配后停止)并用一个空格(" ")替换每个匹配.


Ada*_*ant 18

对于字符串

"    this  is my   string       "
Run Code Online (Sandbox Code Playgroud)

您可能希望将多余的空格设为单个空格,但完全删除前导和尾随空格.为此,添加另一个.replace

s.replace(/\s+/g, " ").replace(/^\s|\s$/g, "");
Run Code Online (Sandbox Code Playgroud)

对于

"this is my string"
Run Code Online (Sandbox Code Playgroud)

更新

s.replace(/\s+/g, " ").trim()
Run Code Online (Sandbox Code Playgroud)

谢谢,@ Pier-Luc Gendreau

  • 哦,是的,就像我说的那样,它删除了前导和尾随空格,因此它会让你的实现稍微清晰一些.`s.replace(/\s +/g,"").trim()` (3认同)