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.

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
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.
Posts created 175

One thought on “Check If String Contains Exact Match in JavaScript

Leave a Reply

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

Related Posts

Begin typing your search term above and press enter to search. Press ESC to cancel.

Back To Top
mariobet - supertotobet - escort -

takip7.com

- milanobet giriş - gizabet giriş -
perabet giriş
- betkanyon giriş -

jojobet giriş

We are now accepting guest posting and creation of back-links.
This is default text for notification bar