用于检查特殊字符的JavaScript代码 [英] javascript code to check special characters
问题描述
我有JavaScript代码来检查特殊字符是否在字符串中。该代码在Firefox中运行良好,但在Chrome中无效。在Chrome中,即使字符串不包含特殊字符,也表示它包含特殊字符。
I have JavaScript code to check if special characters are in a string. The code works fine in Firefox, but not in Chrome. In Chrome, even if the string does not contain special characters, it says it contains special characters.
var iChars = "~`!#$%^&*+=-[]\\\';,/{}|\":<>?";
for (var i = 0; i < chkfile.value.length; i++)
{
if (iChars.indexOf(chkfile.value.charAt(i)) != -1)
{
alert ("File name has special characters ~`!#$%^&*+=-[]\\\';,/{}|\":<>? \nThese are not allowed\n");
return false;
}
}
假设我要上传文件 desktop.zip
来自任何Linux / Windows机器。
在Firefox中, chkfile.value
的值是 desktop.zip
,但在Chrome中,值 chkfile.value
是 c://fakepath/desktop.zip
。如何从 chkfile.value
中删除 c:// fakepath /
?
Suppose I want to upload a file desktop.zip
from any Linux/Windows machine.
The value of chkfile.value
is desktop.zip
in Firefox, but in Chrome the value of chkfile.value
is c://fakepath/desktop.zip
. How do I get rid of c://fakepath/
from chkfile.value
?
推荐答案
您可以使用测试字符串/ docs / JavaScript / Guide / Regular_Expressionsrel =noreferrer>正则表达式:
You can test a string using this regular expression:
function isValid(str){
return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}
这篇关于用于检查特殊字符的JavaScript代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!