94

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
3
  • Did you intend to write "var r = /./;"? Commented Jan 15, 2009 at 15:49
  • I intended to write /a/ (: thanks. Commented Jan 15, 2009 at 16:17
  • Possible duplicate of Regex - Match whole string Commented Dec 14, 2016 at 16:19

6 Answers 6

174

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];
}
Sign up to request clarification or add additional context in comments.

1 Comment

See svante's answer below as well, since it give an explanation as to why this works.
41

Write your regex differently:

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

Comments

17

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.

Comments

1

In case anyone receives an error like

Syntax Error: Invalid regular expression

by using the .match() function. You could always go back to the roots: !!note this code is for matchin an exact string, if you want to search for an exact phrase in a string, you should filter it before hand

console.log("Exact data found: ", hasExactString("?hello", "?hello"))

console.log("Exact data found: ", hasExactString("?hello", "?helloBye"))


function hasExactString(data, searchTerm) {
    console.log("search for ", searchTerm, " in ", data);
    data = data.toLowerCase(); //if search term should be case insensitive
    const searchExpressionLength = searchTerm.length;
    const dataInputLength = data.length;
    if (dataInputLength != searchExpressionLength) {
        return false;
    }
    else {
        //search letter by letter -back to the roots
        for (var i = 0; i < searchExpressionLength; i++) {
            if (data[i] != searchTerm[i]) {
                return false;
            }
        }
        return true;
    }
}

...13 years late, but nonetheless^^

Comments

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

1 Comment

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.
-9

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

1 Comment

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}/?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.