如何在javascript中处理(®'¿¡¡À)特殊字符? [英] How to handle (® ´ © ¿ ¡ ° À ) special characters in javascript?

查看:96
本文介绍了如何在javascript中处理(®'¿¡¡À)特殊字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要开发一个javascript函数,不允许字符串中的特殊字符(®©¿¡À)。问题是IE8无法识别字符串中的特殊字符,并在使用indexOf()方法时返回为-1。处理这些特殊字符的正确方法是什么?

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?

推荐答案

只要你的所有编码都正确(你保存文件吗?)作为UTF-8?它是否作为UTF-8服务?),你应该能够包含这些特殊字符。但是,您可以使用 \u 转义JavaScript中的字符,然后是十六进制的字符代码。

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.

这里是您可以使用(例如,在您的JavaScript控制台中)获得转换的实用程序函数:

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;
}

但是,我会接受deceze的建议。如果逃避特殊字符不是一个选项(我总是喜欢逃避剥离,因为它不太可能做一些会惹恼你的用户的事情,比如删除他们名字中的字母(免责声明:我的名字有'í> 'in it)),使用正则表达式使用 String 替换方法。这个将删除任何非ASCII字符:

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, '');

这篇关于如何在javascript中处理(®'¿¡¡À)特殊字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆