JavaScript-Check-If-String-Contains-Exact-Match.png

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.

Method-1

Live View:

https://jsfiddle.net/PHPCODERTECH/nzd7etcr/

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);
break;
}
}

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

Method-2

Live View:

jsfiddle.net/PHPCODERTECH/fk3y207v/

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: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/RegExp

Also Check:

Happy Coding..!

Was this article helpful?
YesNo

By Bikash

My name is Bikash Kr. Panda. I own and operate PHPCODER.TECH. I am a web Programmer by profession and working on more than 50 projects to date. Currently I am working on the web-based project and all the CMS and frameworks which are based on PHP.

2 thoughts on “Check If String Contains Exact Match in JavaScript”

Leave a Reply

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