与JavaScript匹配确切字符串
问题描述:
如何测试RegEx是否与字符串完全匹配?与JavaScript匹配确切字符串
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];
}
答
写您的正则表达式是不同的:
var r = /^a$/;
r.test('a'); // true
r.test('ba'); // false
答
如果你不使用任何占位符(如以 “完全”,似乎暗示),字符串比较instea如何d?
如果确实使用占位符,^
和$
分别与字符串的开头和结尾匹配。
答
var data = {"values": [
{"name":0,"value":0.12791263050161572},
{"name":1,"value":0.13158780927382124}
]};
//JSON to string conversion
var a = JSON.stringify(data);
// replace all name with "x"- global matching
var t = a.replace(/name/g,"x");
// replace exactly the value rather than all values
var d = t.replace(/"value"/g, '"y"');
// String to JSON conversion
var data = JSON.parse(d);
你打算写“var r = /./;”吗? – Prestaul 2009-01-15 15:49:49
我打算写/ a /(:谢谢。 – 2009-01-15 16:17:46