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; } }
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
?
To check if a string contains special characters, call the test() method on a regular expression that matches any special character. The test method will return true if the string contains at least 1 special character and false otherwise. Copied!
Click Start, point to Settings, click Control Panel, and then click Add/Remove Programs. Click the Windows Setup tab. Click System Tools (click the words, not the check box), and then click Details. Click to select the Character Map check box, click OK, and then click OK.
You can check if a JavaScript string contains a character or phrase using the includes() method, indexOf(), or a regular expression. includes() is the most common method for checking if a string contains a letter or series of letters, and was designed specifically for that purpose.
You can test a string using this regular expression:
function isValid(str){ return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With