admin管理员组

文章数量:1379495

I need to to develop a javascript function to not allow special character (® ´ © ¿ ¡ ° À ) from the string. The problem is IE8 not recognize the special characters in the string and returning as -1 when using indexOf() method. What is the correct way to handle these special characters?

I need to to develop a javascript function to not allow special character (® ´ © ¿ ¡ ° À ) from the string. The problem is IE8 not recognize the special characters in the string and returning as -1 when using indexOf() method. What is the correct way to handle these special characters?

Share Improve this question asked Jun 9, 2010 at 9:18 rajaraja 1012 silver badges3 bronze badges 2
  • Not sure - isn't this encoding related issue? – nothrow Commented Jun 9, 2010 at 9:27
  • 4 Just as general advise: Don't not allow special characters, instead allow a certain set of characters. It's virtually impossible to list all the "special characters" you don't want, it's much easier to specify the ones you do want. – deceze Commented Jun 9, 2010 at 9:34
Add a ment  | 

3 Answers 3

Reset to default 4

As long as all your encodings are correct (are you saving the file as UTF-8? Is it being served as UTF-8?), you should be able to include these special characters. However, you can escape characters in JavaScript with \u, followed by the character code in hex.

Here's a utility function that you can use (say, in your JavaScript console) to get the conversion:

function escapeForCharacter(character){
    var escape = character.charCodeAt('0').toString(16);
    while(escape.length < 4){ escape = '0' + escape; }
    return '\\u'+escape;
}

But, I'd take deceze's advice. If escaping special characters isn't an option (I always prefer escaping over stripping, because it's far less likely to do something that'll annoy your users, like removing letters from their names (disclaimer: my name has an 'í' in it)), use a String's replace method with a regular expression. This one will remove any non-ASCII characters:

string.replace(/[^\u0020-\u007a]/g, '');
var c = "® ´ © ? ! ° A ";
alert(c.indexOf('©'));

works for me correctly. Only difference is between encodings -> in Win1250 it returns 4, in utf-8 6

(in IE)

You can use regexp and function match and replace

本文标签: How to handle (174 180 169 191 161 176 192 ) special characters in javascriptStack Overflow