[英]Allow only certain character in string. Javascript
I have no idea, why this simple code is not working. 我不知道,为什么这个简单的代码不起作用。 I am planning to match a string against the allowed pattern.
我打算将字符串与允许的模式匹配。 The string should ONLY have
az
, AZ
, 0-9
, _
(underscore), .
该字符串应该只有
az
, AZ
, 0-9
, _
(下划线) .
(dot) , -
(hiphen). (点),
-
(hiphen)。
Below is code: 以下是代码:
var profileIDPattern = /[a-zA-Z0-9_.-]./;
var str = 'Heman%t';
console.log('hemant',profileIDPattern.test(str));
The code logs 'true' for below string, although these string DOES NOT match the pattern. 代码在下面的字符串中记录'true',尽管这些字符串与模式不匹配。
'Heman%t' -> true
'#Hemant$' -> true
I dont know what is the problem. 我不知道是什么问题。
Try changing it to this RegExp ( /^[a-zA-Z0-9_.-]*$/
): 尝试将其更改为此RegExp(/
/^[a-zA-Z0-9_.-]*$/
):
var profileIDPattern = /^[a-zA-Z0-9_.-]*$/; var str1 = 'Hemant-._67%' var str2 = 'Hemant-._67'; console.log('hemant1',profileIDPattern.test(str1)); console.log('hemant2',profileIDPattern.test(str2));
Issues : [a-zA-Z0-9_.-]
will match any character inside []
and .
问题:
[a-zA-Z0-9_.-]
将匹配[]
和中的任何字符.
will match anything after so basically it will match the mention character and any other character 将匹配任何东西,所以基本上它将匹配提及字符和任何其他字符
Use ^
and $
anchor to mention start and end of match and remove .
使用
^
和$
anchor来提及匹配的开始和结束并删除.
^[a-zA-Z0-9_.-]+
: starting with any given value inside []
^[a-zA-Z0-9_.-]+
:从[]
内的任何给定值开始
[a-zA-Z0-9_.-]+$
: one or more matches and $
to end the match [a-zA-Z0-9_.-]+$
:一场或多场比赛, $
结束比赛
var profileIDPattern = /^[a-zA-Z0-9_.-]+$/; console.log('hemant', profileIDPattern.test('Heman%t')); // no match - console.log('hemant-._', profileIDPattern.test('hemant-._')); // valid match console.log('empty', profileIDPattern.test('')); // no match ,empty
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.