3

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.

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

5 Comments

Hey thanks @Arg0n, it worked. Can you please help, what does this * means here. If I am not wrong, then ^ and $ means for start and end of string. I think when I tried last time this type of expression, I have not kept * in it.
@HemantYadav It means 'zero or more' of the chars inside []. If you want 'one or more' change it to +. You are correct about ^ and $.
there is a flaw in your pattern , it will also match empty string , try it ''.test(str1)
@Pavneet_Singh As stated, if he wants 'one or more' change it to +. The question does not mention if empty string is valid or not.
The question does not mention if empty string is valid or not , so read this carefully by OP 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).
2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.