Kynian
Kynian

Reputation: 670

regex in javascript, match only A-z and _?

Hello this is the first time I've worked with regex before and I'm attempting to take a variable entered by the user and see if it is limited to A-Z, a-z, 0-9, and _

this is the code I have so far:

function validateCSV(x){
    var y = document.getElementById('column').value;
    var pattern = new RegExp('^\b\w\b$');
    if(!pattern.test(y)){
       alert("Use only A-Z, a-z, 0-9, or _ in column names.");
       return false;
    }
}

As far as I was aware using \w would match any alphanumeric and underscore but no white space, which is exactly what I wanted. However even if I only have something like test1 or test it still doesn't seem to work correctly, as it still pops up my alert and doesn't let me continue. Any information on this matter would be appreciated.

Upvotes: 0

Views: 3398

Answers (3)

nnnnnn
nnnnnn

Reputation: 150040

The problem is that you are defining your regex from a string literal, which means the backslashes need to be escaped. You need:

new RegExp('^\\b\\w\\b$');

Or just use a regex literal:

var pattern = /^\b\w\b$/;

Which leads to your next problem: the regex will match a single \w character. You need to follow that with * to match zero or more, or a + to match one or more.

And the \b parts aren't needed at all:

var pattern = /^\w*$/;

Demo: http://jsfiddle.net/VFyug/

In general, defining a regex using new RegExp() and a string is clunkier than a regex literal and I would only use it if the regex actually is coming from a string variable because, e.g., it needs to include text entered by the user.

Upvotes: 1

Rohit Jain
Rohit Jain

Reputation: 213261

You are missing a quantifier, and you should use regex literal:

/^\w+$/

Upvotes: 6

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324650

Your current regex is looking for a single word character (by definition, \b will assert to true when used at the start and end of the match).

I think the regex you're looking for is /^[a-z0-9_]+$/i

Note that you can use different things for that +:

  • + one or more characters
  • * zero or more characters, basically same as + but also allows empty string
  • {5} exactly five characters
  • {3,16} between three and sixteen characters (inclusive)

Vary as needed!

Upvotes: 3

Related Questions