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
Use the test() method to check if a regular expression matches an entire string, e.g. /^hello$/. test(str) . The caret ^ and dollar sign $ match the beginning and end of the string. The test method returns true if the regex matches the entire string, and false otherwise.
The includes() method returns true if a string contains a specified string. Otherwise it returns false .
There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.
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]; }
Write your regex differently:
var r = /^a$/; r.test('a'); // true r.test('ba'); // false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With