最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Regex to check if string contains Alphanumeric Characters and Spaces only - javascript - Stack Overflow

programmeradmin5浏览0评论

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!

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!

Share Improve this question asked Sep 9, 2013 at 5:51 JoeJoe 8,27214 gold badges60 silver badges96 bronze badges 1
  • Oops I deleted the comment right before your response, I thought the answers were sufficient! – Nasser Al-Shawwa Commented Sep 9, 2013 at 5:59
Add a comment  | 

2 Answers 2

Reset to default 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.

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
发布评论

评论列表(0)

  1. 暂无评论