0

I am a newbie in regular expressions. I have a problem with this one. I need to add chars from addons variable as allowed characters to the next regex re.

var addons = '_-';
re = new RegExp(/^[a-zA-Z]+$/i);

console.log('match a', re.test('a'));
console.log('match a_', re.test('a_'));
console.log('no match 9', re.test('9'));
console.log('no match 9_', re.test('9_'));

Any suggestions? Thanks.

1
  • Are the addons characters only allowed at the end? Or in any position? Commented Nov 11, 2014 at 9:42

1 Answer 1

1

You need to construct the regex allowing those characters too:

var addons = '_-';
    re = new RegExp('^[a-zA-Z]+['+addons+']?$','i');

console.log('match a', re.test('a'));
console.log('match a_', re.test('a_'));
console.log('no match 9', re.test('9'));
console.log('no match 9_', re.test('9_'));

That will test for any of the characters in addons (the brackets), and they're not required (the ?).

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

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.