regex - Allow only certain character in string. Javascript - Stack Overflow

I have no idea, why this simple code is not working. I am planning to match a string against the allowe

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 badges
Add a ment  | 

2 Answers 2

Reset to default 6

Try 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

相关推荐

  • regex - Allow only certain character in string. Javascript - Stack Overflow

    I have no idea, why this simple code is not working. I am planning to match a string against the allowe

    8天前
    10

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信