[英]Validate if a string contains only some characters in javascript
I know this question has been asked here many times, but mine is a tad different.我知道这个问题在这里被问过很多次,但我的有点不同。 I do not want to validate if the string is alphanumeric, I just need it to only consist of a few characters, let's say letters: A, B, a, b and this symbol >.
我不想验证字符串是否为字母数字,我只需要它只包含几个字符,比如说字母:A、B、a、b 和这个符号 >。 Is it possible with regex?
正则表达式可以吗?
A simple example:一个简单的例子:
var isValidString = stringToValidate.match(/^[AaBb>]*$/) !== null;
Explanation:解释:
String.prototype.match() can be called on any string and it will return an array, if the regex matched (containing the matched substrings) or null. String.prototype.match()可以在任何字符串上调用,如果正则表达式匹配(包含匹配的子字符串)或 null,它将返回一个数组。
Wrapping the regular expression between caret ( ^
) and dollar ( $
) signs will ensure, that you check the string in full length.在插入符号 (
^
) 和美元 ( $
) 符号之间包装正则表达式将确保您检查全长字符串。
You can add any characters between square brackets as you like, it will only match those.您可以根据需要在方括号之间添加任何字符,它只会匹配那些字符。
Yes, you could do something like this.是的,你可以做这样的事情。
/(?![ABC])./g
This will match anything that ISNT A, B or C. Meaning that if it gets a match, your validation should fail.这将匹配任何 ISNT A、B 或 C。这意味着如果匹配,您的验证应该失败。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.