简体   繁体   English

如何用JavaScript中的其他东西替换输入中的非Ascii字符

[英]How to replace non-Ascii characters from input with something else in JavaScript

I am implementing a chat-function to a JavaScript game using WebSocket. 我正在使用WebSocket为JavaScript游戏实现聊天功能。 I want to replace non-ascii characters the user has written in the input textfield with other letters. 我想用其他字母替换用户在输入文本字段中编写的非ascii字符。 Ä is replaced with a and Ö is replaced with o. Ä用a代替,Ö用o代替。 And every other non-ascii characters should be replaced by "". 其他所有非ascii字符应替换为“”。

var message = document.getElementById("write_message").value;
message = message.replace(/ä/g, "a").replace(/ö/g, "o");
message = message.replace(/^[\000-\177]/g, "");
ws.send("M" + message);

I tried even simpler versions of the above code, but somehow all user input seemed to be replaced. 我尝试了上述代码的更简单版本,但不知何故,所有用户输入似乎都被替换了。 Even ascii-characters. 即使是ascii字符。 I found the regular expression from another Stackoverflow question. 我从另一个Stackoverflow问题中找到了正则表达式。

you have to know the charset of the supporting html page. 你必须知道支持html页面的charset。 depending on whether it's unicode or some 8bit charser, use \\uzzzz or \\xzz to match chars where z represents a hex digit. 根据它是unicode还是8bit charser,使用\\uzzzz\\xzz匹配字符,其中z表示十六进制数字。

example: message = message.replace(/^[\€-\￿]/g, ""); 例如: message = message.replace(/^[\€-\￿]/g, ""); ascii-fies unicode text. ascii-fies unicode文本。

Your code is correct except that the circumflex ^ must appear after the left bracket [ in order to indicate negation. 你的代码是正确的,除了必须出现在左括号之后的旋律^ [以表示否定。 Otherwise it means something completely different. 否则它意味着完全不同的东西。

However, I think you actually want to map uppercase Ä and Ö to A and O instead of deleting them. 但是,我认为你实际上想要将大写Ä和Ö映射到A和O而不是删除它们。 For this, you would use 为此,你会使用

message = message.replace(/ä/g, "a")
                 .replace(/ö/g, "o")
                 .replace(/Ä/g, "A")
                 .replace(/Ö/g, "O")
                 .replace(/[^\000-\177]/g, "");

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

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