javascript 如何用javascript中的空格替换unicode字符u00A0?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/29850407/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I replace unicode character u00A0 with a space in javascript?
提问by Wryte
I'm looking to replace a bad character that a content editable div uses when a space is added at the end of the input.
我希望替换在输入末尾添加空格时内容可编辑 div 使用的坏字符。
Here is what I've tried
这是我尝试过的
var text = $(this).text();
text.replace(/\u00A0/, " ");
But when I check the value of the last character like this
但是当我像这样检查最后一个字符的值时
text.charCodeAt(text.length-1)
The value is still 160 instead of 32
该值仍然是 160 而不是 32
回答by jcubic
In javascript strings are immutable and replace return new string, try this:
在 javascript 字符串是不可变的并替换返回新字符串,试试这个:
var text = $(this).text();
text = text.replace(/\u00A0/, " ");
or in one line:
或在一行中:
var text = $(this).text().replace(/\u00A0/, " ");
also if you want to replace all instances of the character you need to add g to the regex /\u00A0/g
此外,如果您想替换字符的所有实例,则需要将 g 添加到正则表达式 /\u00A0/g