Подтвердить что ты не робот

Как удалить лишние пробелы с помощью 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>  

Когда я читаю его с помощью jquery, я получаю, что .text() содержит много пробелов и /n между текстом, но без тегов html.

Как удалить все эти пробелы и вернуть чистый текст с помощью jquery или чистого javascript?

4b9b3361

Ответ 1

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

Это использует регулярное выражение (/.../) для поиска одного или нескольких (+) пробельных символов (\s) в тексте элемента (g, глобальный модификатор, который находит все совпадения, а не остановка после первого совпадения) и заменить каждое на одно пространство (" ").

Ответ 2

Для строки

"    this  is my   string       "

Вероятно, вы хотите сделать лишние пробелы пробелами, но полностью удалить верхние и конечные пробелы. Для этого добавьте еще один .replace

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

Для

"this is my string"

Обновление

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

Спасибо, @Pier-Luc Gendreau

Ответ 3

Вы можете удалить все экземпляры конгруэнтных пробелов и новых строк так

// 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 );

Затем, чтобы очистить его и применить к вашему jQuery

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