I have no idea, why this simple code is not working. I am planning to match a string against the allowed pattern.
The string should ONLY have a-z
, A-Z
, 0-9
, _
(underscore), .
(dot) , -
(hiphen).
Below is code:
var profileIDPattern = /[a-zA-Z0-9_.-]./;
var str = 'Heman%t';
console.log('hemant',profileIDPattern.test(str));
The code logs 'true' for below string, although these string DOES NOT match the pattern.
'Heman%t' -> true
'#Hemant$' -> true
I dont know what is the problem.
I have no idea, why this simple code is not working. I am planning to match a string against the allowed pattern.
The string should ONLY have a-z
, A-Z
, 0-9
, _
(underscore), .
(dot) , -
(hiphen).
Below is code:
var profileIDPattern = /[a-zA-Z0-9_.-]./;
var str = 'Heman%t';
console.log('hemant',profileIDPattern.test(str));
The code logs 'true' for below string, although these string DOES NOT match the pattern.
'Heman%t' -> true
'#Hemant$' -> true
I dont know what is the problem.
Share Improve this question edited Jun 2, 2017 at 12:45 Pavneet_Singh 37.4k5 gold badges55 silver badges70 bronze badges asked Jun 2, 2017 at 12:09 Hemant YadavHemant Yadav 3372 gold badges7 silver badges21 bronze badges2 Answers
Reset to default 6Try changing it to this RegExp (/^[a-zA-Z0-9_.-]*$/
):
var profileIDPattern = /^[a-zA-Z0-9_.-]*$/;
var str1 = 'Hemant-._67%'
var str2 = 'Hemant-._67';
console.log('hemant1',profileIDPattern.test(str1));
console.log('hemant2',profileIDPattern.test(str2));
Issues : [a-zA-Z0-9_.-]
will match any character inside []
and .
will match anything after so basically it will match the mention character and any other character
Use ^
and $
anchor to mention start and end of match and remove .
^[a-zA-Z0-9_.-]+
: starting with any given value inside []
[a-zA-Z0-9_.-]+$
: one or more matches and $
to end the match
var profileIDPattern = /^[a-zA-Z0-9_.-]+$/;
console.log('hemant', profileIDPattern.test('Heman%t')); // no match -
console.log('hemant-._', profileIDPattern.test('hemant-._')); // valid match
console.log('empty', profileIDPattern.test('')); // no match ,empty
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744248097a4565035.html
评论列表(0条)