开发者

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'

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜