I’m trying to do something like this…
f = f.replace(' ','   ','gi');
I’ve also tried this…
f = f.replace(/\ {3,}/g,'   ','gi');
How do I replace three spaces with the entity above?
Using \s does not work, I’ve gone through plenty of other Q&As on Stack and nothing has worked.
For clarification this problem stems from XMLSerializer() parsing in addition to serializing and the spaces are at the beginning of each sentence. I use this to make code human readable when editing.
Example placeholder text in the XHTML editor (just a textarea)…
<p>1
  2
  3
  4
  5</p>
…the goal is to serialize this code and either retain the entities (serialization should not parse but all the browsers do) or to “de-parse” by replacing the after-effects.
Also the variable f is a string, not an object or fragment in example.
IMPORTANT!
After using encodeURI turns out these aren’t spaces being generated by XMLSerializer(), (spaces added to make this more readable) %0A %20 %C2 %A0 %C2 %A0.
Here are a couple examples of what the text looks like before and after using encodeURI to determine what the characters were since they weren’t matching spaces thus throwing people off who were trying to help…
%0A%20  First%20and
  First and
The first has two entities inserted, not desirable, I just need one.
  Which is actually
%0A%20 %20Which%20is%20actually
The second output works great using the following from @Bergi…
f = f.replace(/\u00a0/g, ' ')
The following are the unsuccessful attempts with the last one being the successful attempt…
//f = f.replace(/^\s+|\s+$/g,'');
//f = f.replace(' ','   ','gi');
//f = f.replace( / {3,}/g, ' ' );
//f = f.replace(/ {3,}/g,' \u00a0 ');
//f = f.replace(/\ {3,}/g,'   ');
f = f.replace(/ \u00a0/g, '  ');
Instead of replacing with an entitiy, replace with the actual character:
Of course that depends on the output of that string, but usually you should use a string as it should be.
BTW: To make html/xml whitespaces readable, I’d recommend the css property
white-space:pre-wrapinstead of inserting non-breaking characters. They especially make copying the text a horror. Also, if your desire is to show as many whitespaces as in the source, you should replace/\s{2}/with" \u00a0".OK, you have a very curious input: linebreak (
10,%0A,"\n"), a normal space (32,%20," ") and two non-breaking spaces (160,%C2%A0,"\u00a0"). What you could do now to get the desired output:replace(/\u00a0{2}/g, "  ")replace(/\u00a0(.)/g, " $1")replace(/\s{3}/g, "   ")