Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
98
rated 0 times [  104] [ 6]  / answers: 1 / hits: 24981  / 11 Years ago, wed, october 23, 2013, 12:00:00

I am having trouble removing spaces from a string. First I am converting the div to text(); to remove the tags (which works) and then I'm trying to remove the "&nbsp" part of the string, but it won't work. Any Idea what I'm doing wrong.


newStr = $('#myDiv').text();
newStr = newStr.replace(/ /g, '');

$('#myText').val(newStr);


<html>
<div id = "myDiv"><p>remove&nbsp;space</p></div>
<input type = "text" id = "myText" />
</html>

More From » jquery

 Answers
175

When you use the text function, you're not getting HTML, but text: the &nbsp; entities have been changed to spaces.


So simply replace spaces:




var str =  a     b   , // bunch of NBSPs 
newStr = str.replace(/s/g,'');

console.log(newStr)




If you want to replace only the spaces coming from &nbsp; do the replacement before the conversion to text:


newStr = $($('#myDiv').html().replace(/&nbsp;/g,'')).text();

[#74778] Tuesday, October 22, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
tyreem

Total Points: 540
Total Questions: 94
Total Answers: 90

Location: Palestine
Member since Tue, Jul 20, 2021
3 Years ago
;