Wildcard String Comparison in JavaScript
- the Regular Expressions in JavaScript
-
Use the
test()
Method asRegExp
Object in JavaScript -
Use the
substring()
Method in JavaScript -
Use the
substr()
Function in JavaScript -
Difference Between
substring()
andsubstr()
in JavaScript - Wildcard String Comparison in JavaScript
-
Use the
escapeRegex
Function in JavaScript - Conclusion
This article is about JavaScript’s regular expressions, different string methods, and wildcard string comparison in JavaScript. These problems are addressed as:
- What are regular expressions in JavaScript.
- How
substr
andsubstring
are used with regular expressions. - 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);
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;
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;
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'
There are three cases for wildcard patterns before moving to the next character in the Pattern and Text.
- The
?
character matches any single character. - The
*
character matches any sequence of characters. - 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');
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.