简体   繁体   English

正则表达式检查字符串是否仅包含字母数字字符和空格 - javascript

[英]Regex to check if string contains Alphanumeric Characters and Spaces only - javascript

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! 谢谢!

Your problem is that \\w matches all alphanumeric values and underscore. 您的问题是\\w匹配所有字母数字值下划线。

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. 如果reg.test的结果为true ,则字符串验证失败。

Since you are stating you are new to RegExp, I might as well include some tips with the answer. 既然你说你是RegExp的新手,我不妨在答案中加入一些提示。 I suggest the following regexp: 我建议以下正则表达式:

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

Here: 这里:

  1. There is no need for the upper case AZ because of the i flag in the end, which matches in a case-insensitive manner 由于最后的i标志,不需要大写字母AZ,它以不区分大小写的方式匹配
  2. \\d special character represents digits \\ d特殊字符代表数字

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 javascript检查字符串是否仅包含字母数字字符+其他特殊字符 - javascript check if string contains only alphanumeric characters + other special characters Javascript 正则表达式检查字符串是否包含重音字符 - Javascript Regex to check if a string contains accented characters 用 * 替换字符串中的字符,但只有字符而不是空格 JavaScript 正则表达式 - Replace characters in string with *, but only characters not spaces JavaScript regex Javascript 正则表达式检查准确的字母数字和特殊字符 - Javascript regex to check for exact alphanumeric and special characters 检查字符串在JavaScript中是否仅包含空格的最快方法是什么? - What is the fastest way to check if a string contains only white spaces in JavaScript? javascript正则表达式用空格验证字母数字文本并拒绝特殊字符 - javascript regex to validate alphanumeric text with spaces and reject special characters 在javascript中包含字母数字字符和最多一个下划线符号的用户名的正则表达式 - Regex to username that contains alphanumeric characters and at most one underscore symbol in javascript 最有效的正则表达式,用于检查字符串是否包含至少3个字母数字字符 - Most efficient regex for checking if a string contains at least 3 alphanumeric characters 如果字符串仅包含唯一字符,则使用JavaScript进行正则表达式测试 - Regex test in JavaScript if a string contains only unique characters JavaScript 正则表达式仅在字符组之间用空格替换为字母数字 - JavaScript regex replace as alphanumeric with spaces only between character groups
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM