to replace “ ” with  

2019-09-20 12:51发布

问题:

this is my javascript code:

mystring = "this is sample";
nestring = mystring.replace(/ /g," ");

I need nestring ouput "this is sample".

but with the code above, nestring = "this is sample" how can I replace space( ) with &nbsp( )? Many thanks!


re: I embed svg in html. But ie, chrome do not support xml:space=preserve, firefox does. By replace " " with &nbsp, multiple " " will not condense to one " ".

回答1:

You could use the Unicode:

nestring = mystring.replace(/ /g, "\u00a0");

But your example did exactly what you told it to.



回答2:

If you want to replace the characters with character code 32 (0x20) with character with character code 160 (0xA0), you can use the fromCharCode method to create the string to replace with:

nestring = mystring.replace(/ /g, String.fromCharCode(160));


回答3:

Your code works fine, but if you are writing the result to the document you will only see the spaces because they are HTML encoded.

If you alert(nestring); you will see that the spaces are replaced.