Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript regex .test() "Uncaught TypeError: undefined is not a function"

Just trying to use javascript's regex capabilities with the .test() function.

  var nameRegex = '/^[a-zA-Z0-9_]{6,20}$/';

  if(nameRegex.test($('#username').val())) {
      ...
  }

The error is on this line if(nameRegex.test($('#username').val())) {

Debugger breaks there and says "Uncaught TypeError: undefined is not a function". It seems like .test() is not defined? Shouldn't it be?

like image 644
Andrew Avatar asked Jun 01 '14 08:06

Andrew


2 Answers

As it currently stands, nameRegex isn't a regex but a string and String doesn't have test functon which is why you are getting that error.

Remove the quotes around your regex. That is the literal form of regex.

var nameRegex = /^[a-zA-Z0-9_]{6,20}$/; //remove the quotes
like image 184
Amit Joki Avatar answered Oct 06 '22 00:10

Amit Joki


Also, you can create the RegExp from a string by the inherent constructor within javascript.

var nameRegex = '^[a-zA-Z0-9_]{6,20}$';
var regex = new RegExp(nameRegex);
...

if(regex.test(stringToTest)) {
    ...
}

...

MDN Docs :: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

NOTE: don't provide the initial '/' slashes in the string when creating the regex object... It will add them.

like image 36
beauXjames Avatar answered Oct 06 '22 02:10

beauXjames