to replace “ ” with  

北城以北 提交于 2019-12-13 08:49:00

问题


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.



来源:https://stackoverflow.com/questions/8084613/to-replace-with-nbsp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!