LIKE
is commonly used in SQL
for matching strings that contain certain substrings.
For example, this code will match all users
who’s name
contains john
:
SELECT * FROM users WHERE name LIKE '%john%';
Code language: JavaScript (javascript)
A similar thing can be done in JavaScript by using this contains
function:
function contains(str, search, caseInsensitive = false) {
if (typeof str !== 'string') {
str = String(str);
}
if (caseInsensitive) {
str = str.toLowerCase();
search = search.toLowerCase();
}
return str.indexOf(search) !== -1;
}
Code language: JavaScript (javascript)
The contains
function will automatically cast the provided str
to a string
if it is not already a string. Then, the function uses the indexOf
method to check if the str
string contains the search
string. If it does, the function returns true
, otherwise it returns false
.
LIKE
is case-sensitive or case-insensitive depending on the individual database engine used. For example, MySQL is usually case-insensitive and Postgres is case-sensitive.
As such, the above function is optionally case-sensitive or not and that can be controlled with the third parameter. By default the search is case-sensitive. If true
is specified then the search will be done case-insensitive.
contains("Hello, World!", "world"); // returns false
contains("Hello, World!", "WORLD", true); // returns true
Code language: JavaScript (javascript)
Another way to check if a string contains a substring is to use the String.protoype.includes()
method:
"Hello, World!".includes("world") // returns false
"Hello, World!".toLowerCase().includes("world") // returns true
Code language: JavaScript (javascript)
Leave a Reply