[javascript] Matching exact string with JavaScript

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

This question is related to javascript regex

The answer is


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

Write your regex differently:

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

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

Write your regex differently:

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

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

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.


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

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.


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.