JavaScript allows you to match strings in several different ways. Typically, when you match a string in JavaScript, it also matches strings with extra characters before and/or after the string. Sometimes you may need to match exact string in JavaScript. In this article, we will learn how to match exact string in JavaScript.
How to Match Exact String in JavaScript
Let us say you have the following string.
var a ="abcdefghidefjkl";
Typically, we use the following regular expression to match string containing substring def. The following command returns first occurrence.
substr = string.match(/def/);
We use the following expression to get all occurrences.
substr = string.match(/def/g);
But both the above expressions will also match strings that contain extra characters before and after the target expression.
If you only want exact match of target string you need to add ^ and $ before and after the target string respectively.
substr = string.match(/^def$/g);
In the above regular expression, ^ character means starting with and $ sign indicates ending with. So basically, the above regular expression means starting & ending with def, that is, exact match of def string.
In this article, we have learnt how to match exact string in JavaScript.
Also read:
How to Convert Columns to Rows in Pandas
How to Set/Unset Cookie with jQuery
How to Abort AJAX Request in JavaScript/jQuery
How to Get Value of Text Input Field With JavaScript
How to Merge Two Arrays in JavaScript
Related posts:
How to Check if Web Page is Loaded in IFrame or Web Browser
How to Get data-id attribute in jQuery / JavaScript
How to Create Please Wait Loading Animation in jQuery
How to Display Local Storage Data in JavaScript
How to Change Href Attribute of Link Using jQuery
How to Check if Browser Tab is Active
How to Prevent Web Page from Being Loaded in Iframe
How to Find Max Value of Attribute in Array of JS Objects

Sreeram has more than 10 years of experience in web development, Python, Linux, SQL and database programming.