Detects if the string contains an illegal character JS code:
Usually, the Web site input string content is required to be detected, because some characters with a certain risk, will bring some harm to the site, the following describes how to detect whether a string contains illegal characters, the code is as follows:
functionchecks (str) {szmsg= "[#_%& ' \",;: =!^] "; Alertstr=""; for(i=1;i<szmsg.length+1;i++){ if(Str.indexof (Szmsg.substring (i-1,i)) >-1) {Alertstr= "Do not include illegal characters such as [#_%& ' \",;: =!^] "; Break; } } if(Alertstr! = "") {console.log (ALERTSTR); return false; } return true;}varStr= "Antzone=a"; Console.log (checks (str));
The above code to achieve our requirements, the following code to do a simple analysis.
A. Code Comment:
1.function checks (str) {}, the parameter is the string to be detected.
2.szmsg= "[#_%& ' \",;: =!^] ", a string consisting of illegal characters. In particular, the double quotes inside are escaped.
3.alertstr= "", declare a variable and assign an initial value to set the warning prompt.
4.for (i=1;i<szmsg.length+1;i++) {}, traversing each character in a string.
5.if (Str.indexof (szmsg.substring (i-1,i)) >-1), if the string to be detected contains characters from an illegal string.
6.alertstr= "Do not include illegal characters such as [#_%& ' \",;: =!^] ", the warning prompt will be set.
7.break, jump out of the for loop.
two. Related reading:
the 1.indexOf () function can refer to the indexOf () function Usage section of JavaScript .
The 2.substring () function can refer to the substring () method section of the JavaScript string object .
3.break statements can be found in the section on the break and continue statements of JavaScript .
The original address is: http://www.softwhy.com/forum.php?mod=viewthread&tid=12260
For more information, refer to: http://www.softwhy.com/javascript/
Detects if the string contains an illegal character JS code