确定字符串是否有任何不在字符列表中的字符,如果有,哪些字符不匹配?
Determine if string has any characters that aren't in a list of characters and if so, which characters don't match?
我正在研究一个简单的密码验证器,想知道它是否可以在 Regex 或...除了单独检查每个字符之外的任何东西。
基本上,如果用户输入类似 "aaaaaaaaa1aaaaa" 的内容,我想让用户知道字符“1”是不允许的(这是一个超级简单的示例)。
我正在努力避免类似
的事情
if(value.indexOf('@') {}
if(value.indexOf('#') {}
if(value.indexOf('\') {}
可能是这样的:
if(/[^A-Za-z0-9]/.exec(value) {}
有什么帮助吗?
如果你只想检查字符串是否有效,你可以使用 RegExp.test()
- 这比 exec()
更有效,因为它会 return true 当它找到第一个发生次数:
var value = "abc$de%f";
// checks if value contains any invalid character
if(/[^A-Za-z0-9]/.test(value)) {
alert('invalid');
}
如果你想找出哪些字符无效你需要使用String.match()
:
var value = "abc$de%f";
var invalidChars = value.match(/[^A-Za-z0-9]/g);
alert('The following characters are invalid: ' + invalidChars.join(''));
如果我理解您的问题,您可以执行以下操作:
function getInvalidChars() {
var badChars = {
'@' : true,
'/' : true,
'<' : true,
'>' : true
}
var invalidChars = [];
for (var i=0,x = inputString.length; i < x; i++) {
if (badChars[inputString[i]]) invalidChars.push(inputString[i]);
}
return invalidChars;
}
var inputString = 'im/b@d:strin>';
var badCharactersInString = getInvalidChars(inputString);
if (badCharactersInString.length) {
document.write("bad characters in string: " + badCharactersInString.join(','));
}
虽然一个简单的循环就可以完成这项工作,但这里还有另一种使用鲜为人知的 Array.prototype.some
方法的方法。来自 MDN's description of some:
The some() method tests whether some element in the array passes the test implemented by the provided function.
与循环相比的优势在于,一旦测试为阳性,它将停止遍历数组,避免 break
s。
var invalidChars = ['@', '#', '\'];
var input = "test#";
function contains(e) {
return input.indexOf(e) > -1;
}
console.log(invalidChars.some(contains)); // true
我建议:
function isValid (val) {
// a simple regular expression to express that the string must be, from start (^)
// to end ($) a sequence of one or more letters, a-z ([a-z]+), of upper-, or lower-,
// case (i):
var valid = /^[a-z]+$/i;
// returning a Boolean (true/false) of whether the passed-string matches the
// regular expression:
return valid.test(val);
}
console.log(isValid ('abcdef') ); // true
console.log(isValid ('abc1def') ); // false
否则,要显示在字符串中找到但不允许的字符:
function isValid(val) {
// caching the valid characters ([a-z]), which can be present multiple times in
// the string (g), and upper or lower case (i):
var valid = /[a-z]/gi;
// if replacing the valid characters with zero-length strings reduces the string to
// a length of zero (the assessment is true), then no invalid characters could
// be present and we return true; otherwise, if the evaluation is false
// we replace the valid characters by zero-length strings, then split the string
// between characters (split('')) to form an array and return that array:
return val.replace(valid, '').length === 0 ? true : val.replace(valid, '').split('');
}
console.log(isValid('abcdef')); // true
console.log(isValid('abc1de@f')); // ["1", "@"]
参考文献:
我正在研究一个简单的密码验证器,想知道它是否可以在 Regex 或...除了单独检查每个字符之外的任何东西。
基本上,如果用户输入类似 "aaaaaaaaa1aaaaa" 的内容,我想让用户知道字符“1”是不允许的(这是一个超级简单的示例)。
我正在努力避免类似
的事情if(value.indexOf('@') {}
if(value.indexOf('#') {}
if(value.indexOf('\') {}
可能是这样的:
if(/[^A-Za-z0-9]/.exec(value) {}
有什么帮助吗?
如果你只想检查字符串是否有效,你可以使用 RegExp.test()
- 这比 exec()
更有效,因为它会 return true 当它找到第一个发生次数:
var value = "abc$de%f";
// checks if value contains any invalid character
if(/[^A-Za-z0-9]/.test(value)) {
alert('invalid');
}
如果你想找出哪些字符无效你需要使用String.match()
:
var value = "abc$de%f";
var invalidChars = value.match(/[^A-Za-z0-9]/g);
alert('The following characters are invalid: ' + invalidChars.join(''));
如果我理解您的问题,您可以执行以下操作:
function getInvalidChars() {
var badChars = {
'@' : true,
'/' : true,
'<' : true,
'>' : true
}
var invalidChars = [];
for (var i=0,x = inputString.length; i < x; i++) {
if (badChars[inputString[i]]) invalidChars.push(inputString[i]);
}
return invalidChars;
}
var inputString = 'im/b@d:strin>';
var badCharactersInString = getInvalidChars(inputString);
if (badCharactersInString.length) {
document.write("bad characters in string: " + badCharactersInString.join(','));
}
虽然一个简单的循环就可以完成这项工作,但这里还有另一种使用鲜为人知的 Array.prototype.some
方法的方法。来自 MDN's description of some:
The some() method tests whether some element in the array passes the test implemented by the provided function.
与循环相比的优势在于,一旦测试为阳性,它将停止遍历数组,避免 break
s。
var invalidChars = ['@', '#', '\'];
var input = "test#";
function contains(e) {
return input.indexOf(e) > -1;
}
console.log(invalidChars.some(contains)); // true
我建议:
function isValid (val) {
// a simple regular expression to express that the string must be, from start (^)
// to end ($) a sequence of one or more letters, a-z ([a-z]+), of upper-, or lower-,
// case (i):
var valid = /^[a-z]+$/i;
// returning a Boolean (true/false) of whether the passed-string matches the
// regular expression:
return valid.test(val);
}
console.log(isValid ('abcdef') ); // true
console.log(isValid ('abc1def') ); // false
否则,要显示在字符串中找到但不允许的字符:
function isValid(val) {
// caching the valid characters ([a-z]), which can be present multiple times in
// the string (g), and upper or lower case (i):
var valid = /[a-z]/gi;
// if replacing the valid characters with zero-length strings reduces the string to
// a length of zero (the assessment is true), then no invalid characters could
// be present and we return true; otherwise, if the evaluation is false
// we replace the valid characters by zero-length strings, then split the string
// between characters (split('')) to form an array and return that array:
return val.replace(valid, '').length === 0 ? true : val.replace(valid, '').split('');
}
console.log(isValid('abcdef')); // true
console.log(isValid('abc1de@f')); // ["1", "@"]
参考文献: