I have the following code in JavaScript:
const words = ['Bruno Nobre', 'José Bruno', 'Bruno Ricardo', 'Antônio Bruno']
const searchValue = (data) => data.filter(i => i.startsWith('Bruno'));
const values = searchValue(words)
console.log(values)
Its return will be: ['Bruno Nobre', 'Bruno Ricardo']
Similar to returning the MySQL expression: SELECT * FROM table WHERE name LIKE "Bruno%"
But in MySQL, if I add another wildcard character at the beginning of expression(%Bruno%) I can find the word Bruno anywhere in the string if I want to.
But with the startWiths function in JavaScript I can only filter the texts that start with the expression.
I would like JavaScript to have the same default search behavior as startsWith, but to have the possibility of putting a wildcard character at the beginning (similar to LIKE) to search anywhere in the text if necessary.
How could I do this?
2
Answers
To achieve a similar behavior to the MySQL LIKE operator in JavaScript, you can use regular expressions (regex).
Regular expressions provide powerful pattern matching capabilities that can be used to search for specific patterns within strings.
In your case, you can modify the searchValue function to use a regex pattern instead of the startsWith method. Here’s an example of how you can implement it:
In this example, the pattern variable is a regex pattern that matches any string that starts with "Bruno" (similar to LIKE ‘Bruno%’ in MySQL).
The ^ character denotes the start of the string, .* matches any characters (zero or more times), and "Bruno" is the specific pattern you’re searching for.
By using the match method with the regex pattern, you can filter the array data to find the elements that match the pattern.
If you want to search for "Bruno" anywhere in the string (similar to LIKE ‘%Bruno%’ in MySQL), you can modify the pattern variable as follows:
This pattern matches any string that contains "Bruno" anywhere within it.
Hope this can help you.
Build a regular expression dynamically: