2021年1月2日星期六

Match using predicate function in JavaScript

Notice: This is my first question on StackOverflow (although I've answered before). If you think I haven't clarified something, feel free to tell me in the comments.

You may have heard of the String.prototype.match() function in JavaScript, which searches a string for a match against a regular expression, and returns the matches, as an Array object. Here's an example:

var str = "(list 1 2 foo (list nice 3 56 989 asdasdas))"  console.log(str.match(/\d+/g)) //=>["1", "2", "3", "56", "989"]

However, I need a match-like method that inputs a function in JavaScript. This input function would take in a substring of the original string, and output a boolean telling if the substring is a valid match or not. Here's an example of the intended behavior

    function standardFunc(substr) {         return parseFloat(substr) !== NaN;      }        var str = "(list 1 2 foo (list nice 3 56 989 asdasdas))"      console.log(str.match(standardFunc)) //=>["1", "2", "3", "56", "989"]  

Is there an easy way to emulate this behavior in JavaScript?

https://stackoverflow.com/questions/65545698/match-using-predicate-function-in-javascript January 03, 2021 at 09:00AM

没有评论:

发表评论