Matching strings for similar characters - JavaScript

We are required to write a JavaScript function that accepts two strings and a number n.

The function matches the two strings i.e., it checks if the two strings contains the same characters.

The function returns true if both the strings contain the same character irrespective of their order or if they contain at most n different characters, else the function should return false.

Example

Following is the code ?

const str = 'some random text';
const str2 = 'some r@ndom text';

const deviationMatching = (first, second, num) => {
    let count = 0;
    for(let i = 0; i < first.length; i++){
        if(!second.includes(first[i])){
            count++;
        };
        if(count > num){
            return false;
        };
    };
    return true;
};

console.log(deviationMatching(str, str2, 1));

Output

This will produce the following output in console ?

true

How It Works

The function iterates through each character in the first string and checks if it exists in the second string using includes(). When a character is not found, it increments the count. If the count exceeds the allowed number of differences (n), it returns false immediately.

Additional Example

Let's test with different deviation limits:

const str1 = 'hello';
const str2 = 'hallo';

console.log(deviationMatching(str1, str2, 0)); // false - 'e' not in str2
console.log(deviationMatching(str1, str2, 1)); // true - only 1 different char
console.log(deviationMatching(str1, str2, 2)); // true - within limit
false
true
true

Key Points

  • The function only checks if characters from the first string exist in the second string
  • It doesn't verify character frequencies or positions
  • Returns false as soon as the deviation count exceeds the limit
  • Case-sensitive comparison is performed

Conclusion

This function provides a simple way to check string similarity with a configurable tolerance for different characters. It's useful for fuzzy string matching where minor variations are acceptable.

Updated on: 2026-03-15T23:18:59+05:30

666 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements