8

This is what I have so far:

function checkTitle(){
    reg = /^[\w ]+$/;
    a = reg.test($("#title").val());    
    console.log(a);
}

So far in my tests it catches all special characters except _. How do I catch all special characters including _ in the current function?

I need the string to only have Alphanumeric Characters and Spaces. Appreciate the help cause I am having a hard time understanding regex patterns.

Thanks!

1
  • Oops I deleted the comment right before your response, I thought the answers were sufficient! Commented Sep 9, 2013 at 5:59

2 Answers 2

13

Your problem is that \w matches all alphanumeric values and underscore.

Rather than parsing the entire string, I'd just look for any unwanted characters. For example

var reg = /[^A-Za-z0-9 ]/;

If the result of reg.test is true, then the string fails validation.

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

5 Comments

@TimPietzcker Thanks. Been working with stronger regex libraries lately. Haven't had to deal with unicode in JS yet.
@Phil: If you ever have to, take a look at XRegExp with Unicode plugins.
@Phil what if I want to allow parentheses with this, Please Suggest
@AjaySuwalka wouldn't you just include parentheses in the character class then? [^A-Za-z0-9 ()]
@Phil Thanks, I added it, I was just a little skeptical about adding that whether it would work or not. :
3

Since you are stating you are new to RegExp, I might as well include some tips with the answer. I suggest the following regexp:

/^[a-z\d ]+$/i

Here:

  1. There is no need for the upper case A-Z because of the i flag in the end, which matches in a case-insensitive manner
  2. \d special character represents digits

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.