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 Get Unique Values from Array in JavaScript
How to Measure Time Taken by JS Function to Execute
How to Automatically Scroll to Bottom of Page in JS
How to Display Local Storage Data in JavaScript
How to Check if JavaScript Object Property is Undefined
How to Remove Key from JavaScript Object
How to Add Delay in JavaScript Loop
How to Add 1 Day to Current Date

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