2009-01-15 130 views
28

如何测试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 
+0

你打算写“var r = /./;”吗? – Prestaul 2009-01-15 15:49:49

+0

我打算写/ a /(:谢谢。 – 2009-01-15 16:17:46

回答

59

要么

var r = /^a$/ 

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

写您的正则表达式是不同的:

var r = /^a$/; 
r.test('a'); // true 
r.test('ba'); // false 
8

如果你不使用任何占位符(如以 “完全”,似乎暗示),字符串比较instea如何d?

如果确实使用占位符,^$分别与字符串的开头和结尾匹配。

0
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);