简体   繁体   English

验证字符串是否仅包含 javascript 中的某些字符

[英]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.

相关问题 正则表达式-仅当字符串包含任何其他字符时才允许使用某些字符 - Regex - allow some characters only if the string contains any other characters 验证仅包含一次出现的某些特定 substring 的字符串 - Validate a string that only contains a single occurrence of some specific substring javascript检查字符串是否仅包含字母数字字符+其他特殊字符 - javascript check if string contains only alphanumeric characters + other special characters 如何测试仅包含字母字符和破折号(-)的字符串[javascript] - how to test a string that contains only letter characters and dash(-) [javascript] 正则表达式检查字符串是否仅包含字母数字字符和空格 - javascript - Regex to check if string contains Alphanumeric Characters and Spaces only - javascript 如果字符串仅包含唯一字符,则使用JavaScript进行正则表达式测试 - Regex test in JavaScript if a string contains only unique characters 如何验证包含某些字符的字符串? - How to validate a string contains certain characters? 测试字符串是否只包含字符 - Test if string contains only characters 如何检查给定的字符串是否包含一些指定的特殊字符在javascript中存在或不存在? - How to check given string contains some specified special characters exists or not in javascript? JavaScript正则表达式-匹配一个包含一些字符但不包含其他字符的字符串 - JavaScript Regex - Match a string with that contains some characters and doesn't contain others
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM