Wildcard String Comparison in JavaScript

Tahseen Tauseef Oct 12, 2023
  1. the Regular Expressions in JavaScript
  2. Use the test() Method as RegExp Object in JavaScript
  3. Use the substring() Method in JavaScript
  4. Use the substr() Function in JavaScript
  5. Difference Between substring() and substr() in JavaScript
  6. Wildcard String Comparison in JavaScript
  7. Use the escapeRegex Function in JavaScript
  8. Conclusion
Wildcard String Comparison in JavaScript

This article is about JavaScript’s regular expressions, different string methods, and wildcard string comparison in JavaScript. These problems are addressed as:

  1. What are regular expressions in JavaScript.
  2. How substr and substring are used with regular expressions.
  3. How to use wildcard methods for string comparison in JavaScript.

the Regular Expressions in JavaScript

A regular expression is a search pattern consisting of a series of characters. This search pattern can define what you’re looking for while searching for data in a text.

A regular expression might be as simple as a single character or as complex as a complex pattern. All text search and text replace operations may be performed with regular expressions.

/BlocTAK/x;

In the code line, BlocTAK is a pattern used in a search, and x is a modifier that ensures that the search is case-insensitive.

Use the test() Method as RegExp Object in JavaScript

A RegExp expression method is the test() method. It looks for a pattern in a string and returns true or false based on the outcome.

Code - HTML:

<html>
<body>

<p>Search for "H" in the next paragraph:</p>
<p id="5">Hello World</p>
<p id="data"></p>

</body>
</html>

It can also be added in the header of HTML using the <script> tag also.

Code - JavaScript:

let text = document.getElementById('5').innerHTML;
const pattern = /e/;
document.getElementById('data').innerHTML = pattern.test(text);

Run Code.

Use the substring() Method in JavaScript

The function substring() extracts characters from a string and returns the substring between two indices (positions). The substring() function removes characters from the beginning to the conclusion of a string (exclusive).

The substring() method does not alter the original string. Arguments are switched if the start is bigger than the end, and when the start or end values are less than zero, they are considered 0.

Code - HTML:

<html>
<body>

<p>substring() extracts a part of a string:</p>
<p id="demo"></p>

</body>
</html>

Code - JavaScript:

let text = 'Hello world!';
let result = text.substring(7, 5);

document.getElementById('demo').innerHTML = result;

Run Code.

Use the substr() Function in JavaScript

The substr() function takes a string segment and extracts it. The substr() function takes a given number of characters and returns a defined number of characters.

The substr() will not change the original string. Use a negative start position to remove characters from the string’s end.

Code - HTML:

<html>
<body>

<p>substr() extracts a part of a string:</p>
<p id="data"></p>

</body>
</html>

Code - JavaScript:

let text = 'Hello world!';
let result = text.substr(7, 5);

document.getElementById('data').innerHTML = result;

Run Code.

Difference Between substring() and substr() in JavaScript

You should be cautious not to mix up the substring() and substr() methods since there is a small difference between them. substring() takes two arguments, the starting and ending indexes.

In comparison, substr() takes two arguments, the starting index and the number of characters to include in the returned string.

Code:

let text = 'BlocTAK'
console.log(text.substring(2, 5))  // => "ocT"
console.log(text.substr(2, 3))     // => "ocT"

Wildcard String Comparison in JavaScript

A single character, such as an asterisk (*), is a wildcard character that can be read as several literal characters or an empty string. It is frequently used in file searches since it eliminates the need to input the complete name.

Implement a wildcard pattern matching method with a text and a wildcard pattern to see if the wildcard pattern matches the Text. The matching should go all the way through the Text.

The ? and * can be used in the wildcard pattern.

Code:

function match(first, second) {
  if (first.length == 0 && second.length == 0) return true;

  if (first.length > 1 && first[0] == '*' && second.length == 0) return false;

  if ((first.length > 1 && first[0] == '?') ||
      (first.length != 0 && second.length != 0 && first[0] == second[0]))
    return match(first.substring(1), second.substring(1));

  if (first.length > 0 && first[0] == '*')
    return match(first.substring(1), second) ||
        match(first, second.substring(1));

  return false;
}

function test(first, second) {
  if (match(first, second))
    document.write(
        'Yes' +
        '<br>');
  else
    document.write(
        'No' +
        '<br>');
}

test('He*lo', 'Hello');          // Yes
test('He?lo*', 'HelloWorld');    // Yes
test('*pqrs', 'pqrst');          // No because 't' is not in first
test('abc*bcd', 'abcdhghgbcd');  // Yes
test('abc*c?d', 'abcd');  // No because second must have 2 instances of 'c'

Run Code.

There are three cases for wildcard patterns before moving to the next character in the Pattern and Text.

  1. The ? character matches any single character.
  2. The * character matches any sequence of characters.
  3. The character is not a wildcard. We’ll go to the next character in the Pattern and Text if the current character in the Text matches the current character in the Pattern.

The above code is an example for string matching where one string containing wildcard characters is given, using the first 2 cases.

Use the escapeRegex Function in JavaScript

Use the escapeRegex function to escape any characters with any special meaning in a regular expression.

Code:

function matchRuleShort(str, rule) {
  var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');
  return new RegExp('^' + rule.split('*').map(escapeRegex).join('.*') + '$')
      .test(str);
}

function matchRuleExpl(str, rule) {
  var escapeRegex = (str) => str.replace(/([.*+?^=!:${}()|\[\]\/\\])/g, '\\$1');

  rule = rule.split('*').map(escapeRegex).join('.*');

  rule = '^' + rule + '$'

  var regex = new RegExp(rule);

  return regex.test(str);
}
alert(
    '1. ' + matchRuleShort('bird123', 'bird*') + '\n' +
    '2. ' + matchRuleShort('123bird', '*bird') + '\n' +
    '3. ' + matchRuleShort('123bird123', '*bird*') + '\n' +
    '4. ' + matchRuleShort('bird123bird', 'bird*bird') + '\n' +
    '5. ' + matchRuleShort('123bird123bird123', '*bird*bird*') + '\n' +
    '6. ' + matchRuleShort('s[pe]c 3 re$ex 6 cha^rs', 's[pe]c*re$ex*cha^rs') +
    '\n' +
    '7. ' + matchRuleShort('should not match', 'should noo*oot match') + '\n');

Run Code.

escapeRegex escapes any character that contains any special meaning in a regular expression, and it is always true for any string, grep(regexpEscape(string), string).

Conclusion

In this article, we went through concepts of regular expressions and their objects. Then we focused on string methods substr and substring and their differences.

Moreover, we used these string methods substr() and substring() with wildcard methods in JavaScript. Then, in the end, we used wildcard string comparison in JavaScript using regexp object true() and regexpEscape function.

Related Article - JavaScript String