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
3 Answers
Reset to default 4As 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
版权声明:本文标题:How to handle (® ´ © ¿ ¡ ° À ) special characters in javascript? 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744488012a2608566.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论