0

I'm trying to filter this

Alert me when this account’s current balance goes above $1.

from the list here:

alertTypes = [
 'Alert me when this account’s available balance goes below $1.',
 'Alert me when this account’s current balance goes below $1.',
 'Alert me when this account’s available balance goes above $1.',
 'Alert me when this account’s current balance goes above $1.']

Using this async function

const alertRegEx = "/.*current balance.*above.*/"
const alert = alertTypes.filter(alert => alert.match(alertRegEx))

But im getting the whole list in alert variable. What's my mistake here?

3
  • You regex is not a regex but a string. Try removing the quotes Commented Sep 16, 2021 at 7:19
  • Also, why use async/await? There is no asynchronous code here. Moreover, you cannot use an async function for a .filter() predicate. Commented Sep 16, 2021 at 7:20
  • I just did a shortcut but basically the regex came from a json. say something like { "test" : { "testRegex": "/.*current balance.*above.*/"} } Commented Sep 16, 2021 at 7:25

1 Answer 1

2

Firstly, do not use async in this case as match is not an async function (but even if it was you would not be able to use it in a filter). Then you need to use an literal regular expression,not a string.

And a minor, non-required, change is that you can skip the initial and final .*

const alertTypes = [
 'Alert me when this account’s available balance goes below $1.',
 'Alert me when this account’s current balance goes below $1.',
 'Alert me when this account’s available balance goes above $1.',
 'Alert me when this account’s current balance goes above $1.']



const alertRegEx = /current balance.*above/;
const alerts = alertTypes.filter( alert =>  alert.match(alertRegEx))

console.log(alerts);

Sign up to request clarification or add additional context in comments.

3 Comments

I just clipped this but basically the regex came from a json file. So I had to add the quotes.
Then you could create a regular expression out of it by using const actualRegex = new RegExp(alertRegEx); but you will need to remove the starting & ending /
I will try this. Do I still use the filter function? or the .test now?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.