Check If String Contains Exact Match in JavaScript

To Check If String Contains an Exact Match in JavaScript, we use 2 methods where we use two main JavaScript built-in functions. One is split() and second is RegExp method.

Check If String Contains Exact Match in JavaScript
Check If String Contains Exact Match in JavaScript

Here are 2 steps to Check If String Contains Exact Match using JS,

  1. Using RegExp with replace() function.
  2. Using split() with for loop.

Table of Content


Live View:

Code Explanations:

  • Here we create variables to store some strings and words first.
  • After that, we split all the words from the complete sentence using var words = sentence.split(" ");
  • At the last, we take all the words from sentences using the loop and compare them with the given string.

for (var i = 0; i < words.length; ++i) {
if(words[i] === compare) {
alert("found " + compare);

  • Now you can call the created function with required parameters.


Live View:

Code Explanations:

  • In this method, first, we replace all the spaces and other slashes from the string using replace() JS function.
    • replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&')
  • In the second step, we use regExp or regular expression to check the exact match. Also, we use the above replace functionality inside the regExp object.
    • return new RegExp(\\b${escapeRegExpMatch(match)}\\b).test(str)
  • At last, we match the string with a sentence using the created function.
    • isExactMatch(sentence, keyword)

Here is complete solution of JavaScript String Contains Exact Match.

you can check live view and modify according to you. To know more about regular expression in JavaScript you can check here:

Also Check:

Happy Coding..!

Subscribe For Latest Updates

Sign up to best of PHP Code Solutions, informed analysis and opinions on what matters to you.
Invalid email address
We promise not to spam you. You can unsubscribe at any time.


My name is Bikash Kr. Panda. I own and operate PHPCODER.TECH, my native place in Odisha. I am a Web Programmer by profession and working on more than 50 projects to date. My passion is working on the web-based project using PHP and relate to all CMS and frameworks which is based on PHP.

Leave a Reply

Your email address will not be published. Required fields are marked *