Take the 2-minute tour ×

I am implementing a chat-function to a JavaScript game using WebSocket. I want to replace non-ascii characters the user has written in the input textfield with other letters. Ä is replaced with a and Ö is replaced with o. And every other non-ascii characters should be replaced by "".

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. I found the regular expression from another Stackoverflow question.

share|improve this question

2 Answers 2

up vote 1 down vote accepted

you have to know the charset of the supporting html page. depending on whether it's unicode or some 8bit charser, use \uzzzz or \xzz to match chars where z represents a hex digit.

example: message = message.replace(/^[\u0080-\uffff]/g, ""); ascii-fies unicode text.

share|improve this answer
I checked from Chrome's settings that it uses unicode(utf-8). I tried to replace them with "x" according to your code, but it only replaces the first one. "ä" becomes "x" as it should be. However "eä" stays the same. Also "ää" changes to "xä". What could be the problem? –  Teemu Leivo Apr 17 '13 at 14:39
you must remove the caret (^) from your regex as it matches the beginning of the string. –  collapsar Apr 17 '13 at 14:45

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. For this, you would use

                 .replace(/ö/g, "o")
                 .replace(/Ä/g, "A")
                 .replace(/Ö/g, "O")
                 .replace(/[^\000-\177]/g, "");
share|improve this answer

Your Answer


