78

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
user2428118
  • 7,687
  • 4
  • 43
  • 71
Serhat Ozgel
  • 22,946
  • 29
  • 99
  • 137

5 Answers5

149

Either modify the pattern beforehand so that it only matches the entire string:

var r = /^a$/

or check afterward whether the pattern matched the whole string:

function matchExact(r, str) {
   var match = str.match(r);
   return match && str === match[0];
}
Bob Stein
  • 14,529
  • 8
  • 77
  • 98
Jimmy
  • 85,597
  • 17
  • 118
  • 137
33

Write your regex differently:

var r = /^a$/;
r.test('a'); // true
r.test('ba'); // false
Serhat Ozgel
  • 22,946
  • 29
  • 99
  • 137
Prestaul
  • 80,402
  • 10
  • 82
  • 84
14

If you do not use any placeholders (as the "exactly" seems to imply), how about string comparison instead?

If you do use placeholders, ^ and $ match the beginning and the end of a string, respectively.

Svante
  • 49,447
  • 11
  • 79
  • 121
-4
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);
Aravind Cheekkallur
  • 3,099
  • 6
  • 25
  • 40
  • It can be solved simply by regex expression, this approach is very costly and it may did not go well. depending on input. Please consider using regex. – ahsan ayub Nov 17 '21 at 13:48
-11

Here's what is (IMO) by far the best solution in one line, per modern javascript standards:

const str1 = 'abc';
const str2 = 'abc';
return (str1 === str2); // true


const str1 = 'abcd';
const str2 = 'abc';
return (str1 === str2); // false

const str1 = 'abc';
const str2 = 'abcd';
return (str1 === str2); // false
Dharman
  • 26,923
  • 21
  • 73
  • 125
kp123
  • 1,034
  • 1
  • 13
  • 22
  • 4
    This is nonsense, it has nothing to do with RegExp. How does this address the question if you e.g. want to test if `str1` exactly matches `/[a-z]{3}/`? – JHH Oct 15 '20 at 11:05