简体   繁体   中英

How to remove extra white spaces using javascript or jquery?

I got HTML element contains this:

  <!--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>  

When i read it using jquery i get the .text() contains a lot of spaces and /n in between the text but without the html tags.

How to remove all these white spaces and return the clean text using jquery or pure javascript?

element.text().replace(/\s+/g, " ");

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

For the string

"    this  is my   string       "

You probably want to make the excessive spaces single spaces, but remove the leading and trailing spaces entirely. For that, add another .replace

s.replace(/\s+/g, " ").replace(/^\s|\s$/g, "");

For

"this is my string"

Update

s.replace(/\s+/g, " ").trim()

Thanks, @Pier-Luc Gendreau

You can remove all instances of congruent whitespace and newlines like so

// Note: console.log() requires Firebug

var str = '    this  is \n    some text \r don\'t \t you    know?   ';
console.log( str );

str = str.replace( /[\s\n\r]+/g, ' ' );
console.log( str );

Then to clean it up and apply it to your jQuery

$.trim( $element.text().replace( /[\s\n\r]+/g, ' ' ) )

This code working fine, Here I have remove extra white spaces in TextEditor.

var htmlstring =   $("#textareaCode").html().replace(/(&nbsp;)*/g, "");

for more Deatils refer: http://www.infinetsoft.com/Post/How-to-remove-nbsp-from-texteditor-in-jQuery/1226#.V0J-2fl97IU

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