2

I've found a lot questions on StackOverflow about how to do this, but it's just not working for me.

var username = "abcdefg";
var min_length = 3;
var max_length = 24;
var regex = new RegExp('^[\w.-]{' + min_length + ',' + max_length + '}$');
if (regex.test(username))
    document.getElementById('status').innerHTML = 'match';
else
    document.getElementById('status').innerHTML = 'no match';

I've also tried with slashes before and after:

new RegExp('/^[\w.-]{' + min_length + ',' + max_length + '}$/')

And I've also tried with double quotes instead of single quotes (not sure if regex treats single quotes as reserved or something).

If I remove the quotes and put in numbers for the variables it works fine:

new RegExp(/^[\w.-]{3,24}$/)

jsFiddle: http://jsfiddle.net/88ef3/

5
  • And you're sure that works if you just type the numbers instead ? Commented Jun 22, 2014 at 16:25
  • Check this out: jsfiddle.net/88ef3/1 Commented Jun 22, 2014 at 16:26
  • you are including / in your pattern in the jsfiddle Commented Jun 22, 2014 at 16:27
  • yes, but I've tried it with and without Commented Jun 22, 2014 at 16:27
  • look here jsfiddle.net/Yp4sp Commented Jun 22, 2014 at 16:28

3 Answers 3

3

When you use RegExp constructor to build a regular expression from a string, you must escape slashes:

new RegExp('^[\\w.-]{' + min_length + ',' + max_length + '}$');

Remember that a slash in a javascript string is used to escape, but here you want the slah as a character, so you must escape itself.

Demo

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

3 Comments

That did it! Thank you. I'll accept this after the 10 minute period is up.
@Gavin also note from other comments that you do not use / in RegExp constructor, because the / is the delimiter for regex literals.
That's what I figured, I just couldn't figure out why this wasn't working so I tried everything I could think of.
1
new RegExp('^[\\w.-]{' + min_length + ',' + max_length + '}$')

1 Comment

Thanks, but Oriol beat you to it :)
0

This may help

var username = "abcdefg";
var min_length = 3;
var max_length = 24;
var str1='^[\\w.-]{'+min_length+','+max_length+'}$';
var regex = new RegExp(str1,"i");
if (regex.test(username))
    document.getElementById('status').innerHTML = 'match';
else
    document.getElementById('status').innerHTML = 'no match';

http://jsfiddle.net/Et7J8/

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.