2

I'm reading out a text from an HTML element and saving it in an JS array, but if the user puts in more then one empty space it is converted into a non breakable space symbol. Later on if I read out the array it prints out "&nbsp" instead of an empty space. How can I detect an empty space?

&nbsp  //instead of an empty space

I tried replace, but it does not work:

myText.replace(/( )*/g," ")
daisy
  • 615
  • 2
  • 8
  • 15

1 Answers1

4

Regex notation table for whitespace

\x20 – standard space ‘\s’
\xC2\xA0 – ‘ ’
\x0D -  ‘\r’
\x0A – new Line or ‘\n’
\x09 – tab or ‘\t’ 

JS table notation :

String.fromCharCode(160) -  

Now use it for replacing all your characters, add more if you want to remove newline or carriage return

var re = '/(\xC2\xA0/| )';
x = x.replace(re, ' ');

you can also use

var re = '/(\xC2\xA0/| )';
x = x.replace(re, String.fromCharCode(160));

Try this tool to test more Regular expression www.rubular.com

Notepad
  • 1,659
  • 1
  • 12
  • 14
  • 1
    You can also use $(selector).html() to fetch data along with all space if you are using jquery. – Notepad Apr 28 '13 at 18:11
  • `var tmp = document.createElement('div'); tmp.innerHTML = ' '; var nonBreakableSpaceChar = tmp.innerText;` – jave.web Mar 17 '21 at 16:50