我不知道为什么这个简单的代码不起作用。我打算将字符串与允许的模式进行匹配。
字符串应仅包含 a-z
、A-Z
、0-9
、_
(下划线)、。
(点),-
(连字符)。
代码如下:
var profileIDPattern = /[a-zA-Z0-9_.-]./;
var str = 'Heman%t';
console.log('hemant',profileIDPattern.test(str));
代码为以下字符串记录“true”,尽管这些字符串与模式不匹配。
'Heman%t' -> true
'#Hemant$' -> true
不知道是什么问题
最佳答案
尝试将其更改为此 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));
关于javascript - 只允许字符串中的特定字符。 Javascript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44328614/