Hemant Yadav
Hemant Yadav

Reputation: 337

Allow only certain character in string. Javascript

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.

Upvotes: 3

Views: 3602

Answers (2)

Pavneet_Singh
Pavneet_Singh

Reputation: 37404

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

Upvotes: 2

Arg0n
Arg0n

Reputation: 8423

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));

Upvotes: 6

Related Questions