简体   繁体   English

替换为“”

[英]to replace “ ” with  

this is my javascript code: 这是我的JavaScript代码:

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(   )? 但是使用上面的代码, nestring = "this is sample"我如何用&nbsp(   )替换空格(     )? Many thanks! 非常感谢!


re: I embed svg in html. 回复:我将svg嵌入html中。 But ie, chrome do not support xml:space=preserve, firefox does. 但是,chrome不支持xml:space = preserve,而Firefox支持。 By replace " " with &nbsp, multiple " " will not condense to one " ". 通过用&nbsp替换“”,多个“”不会凝结为一个“”。

You could use the Unicode: 您可以使用Unicode:

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

But your example did exactly what you told it to. 但是您的示例完全符合您的要求。

如果要将字符代码为32(0x20)的字符替换为字符代码为160(0xA0)的字符,则可以使用fromCharCode方法创建要替换为的字符串:

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

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. 您的代码可以正常工作,但是如果将结果写入文档,则只能看到空格,因为它们是HTML编码的。

If you alert(nestring); 如果你alert(nestring); you will see that the spaces are replaced. 您会看到空格已替换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM