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 strin开发者_JS百科g and returning as -1 when using indexOf() method. What is the correct way to handle these special characters?
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
精彩评论