Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
466 views
in Technique[技术] by (71.8m points)

javascript - 检查字符串是否与JS中的正则表达式匹配(Check whether a string matches a regex in JS)

I want to use JavaScript (can be with jQuery) to do some client-side validation to check whether a string matches the regex:(我想使用JavaScript(可以使用jQuery)进行一些客户端验证来检查字符串是否与正则表达式匹配:)

^([a-z0-9]{5,})$ Ideally it would be an expression that returned true or false.(理想情况下,它将是一个返回true或false的表达式。) I'm a JavaScript newbie, does match() do what I need?(我是一个JavaScript新手, match()做我需要的吗?) It seems to check whether part of a string matches a regex, not the whole thing.(它似乎检查字符串的一部分是否匹配正则表达式,而不是整个事物。)   ask by Richard translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Use regex.test() if all you want is a boolean result:(如果你想要的只是一个布尔结果,请使用regex.test() :)

console.log(/^([a-z0-9]{5,})$/.test('abc1')); // false console.log(/^([a-z0-9]{5,})$/.test('abc12')); // true console.log(/^([a-z0-9]{5,})$/.test('abc123')); // true ...and you could remove the () from your regexp since you've no need for a capture.(...你可以从正则表达式中删除() ,因为你不需要捕获。)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...