使用JavaScript匹配完全字符串 [英] Matching exact string with JavaScript

查看:1609
本文介绍了使用JavaScript匹配完全字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何测试RegEx是否与字符串完全匹配

How can I test if a RegEx matches a string exactly?

var r = /a/;
r.test("a"); // returns true
r.test("ba"); // returns true
testExact(r, "ba"); // should return false
testExact(r, "a"); // should return true


推荐答案

var r = /^a$/

function matchExact(r, str) {
   var match = str.match(r);
   return match != null && str == match[0];
}

这篇关于使用JavaScript匹配完全字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆