javascript regular expressions
h开发者_如何学Pythonow can i not allow these chars:
\ / " ' [ ] { } | ~ ` ^ &
using javascript regular expression pattern?
Check a string contains one of these characters:
if(str.match(/[\\\/"'\[\]{}|~`^&]/)){
alert('not valid');
}
Validate a whole string, start to end:
if(str.match(/^[^\\\/"'\[\]{}|~`^&]*$/)){
alert('it is ok.');
}
To specifically exclude just those characters (Just prefix with backslash)
const isNotSpecial = /[^\\\/\"\'\[\]\{\}\|\~\`\^\&]/.test(myvalue);
To generally exclude all special characters
const isNotSpecial = /[^\W]/.test(myvalue);
Another solution is encoding these special characters into the regular expression format.
Using package regexp-coder
const { RegExpCoder } = require('regexp-coder');
console.log(RegExpCoder.encodeRegExp('a^\\.()[]?+*|$z'));
// Output: 'a\^\\\.\(\)\[\]\?\+\*\|\$z'
精彩评论