有一个匹配器var matcher = 'NNN#DDD'
。在此,N代表字母(a-z或A-Z),D代表数字(0-9)。
有没有办法在javascript / jQuery中将用户输入与上面的匹配器匹配?
例如:
var user_input = 'abc#123' # matched
var user_input = 'ab1#123' # non matched
注意:由于匹配器是用户输入,因此匹配器不能更改为正则表达式
答案 0 :(得分:3)
UPDATE: After the question was clarified, it turns out the matcher needs to be input by a user. If you really don't want to require a regular expression from the user (perhaps because you want it simpler?) then I suggest you define your own format rules for what the matcher can be like. Then, you should convert the string they input to a regex for internal use.
For example, if the user can allow letters, numbers, or certain special characters, you could define it as (using your example): "Enter N to represent each character, D to represent each digit, and any special characters from the following set: (% #)."
If the user entered "NN#DDD%ND", you would convert that string to a regex.
var userMatcher = 'NN#DDD%ND';
var matcherRegex = '';
var matcherMap = {
'N': '[a-zA-Z]',
'D': '[0-9]',
'#': '#',
'%': '%'
};
var regexValue;
for(var i in userMatcher) {
regexValue = matcherMap[userMatcher[i]];
if(regexValue === undefined) {
throw new Error('Invalid matcher!');
}
matcherRegex += regexValue;
}
matcherRegex = new RegExp(matcherRegex);
var testInput = ['ab#123%H2', 'a1#123%H2'];
for (var i = 0; i < testInput.length; i++) {
if (testInput[i].match(matcherRegex)) {
console.log(testInput[i] + ' matches!');
} else {
console.log(testInput[i] + ' doesn\'t match...');
}
}
答案 1 :(得分:2)
Maybe you would like to mask Masked Input Plugin?
<input type="text" id="masked" />
and just invoke the plugin:
$("#masked").mask("aaa#999");