Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 
like image 709
Serhat Ozgel Avatar asked Jan 15 '09 15:01

Serhat Ozgel


People also ask

How do I match a whole string in JavaScript?

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.

How do I check if a string contains a specific word in JavaScript?

The includes() method returns true if a string contains a specified string. Otherwise it returns false .

How do you match strings?

There are three ways to compare String in Java: By Using equals() Method. By Using == Operator. By compareTo() Method.


2 Answers

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]; } 
like image 67
Jimmy Avatar answered Oct 09 '22 08:10

Jimmy


Write your regex differently:

var r = /^a$/; r.test('a'); // true r.test('ba'); // false 
like image 34
Prestaul Avatar answered Oct 09 '22 09:10

Prestaul