Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JavaScript: Can I use the filter function with regular expressions?

I tried to find a similar question to avoid creating a duplicate and I couldn’t, but I apologise if I missed any. I've just started learning how to code and I've encountered this problem:

With JavaScript, I want to use the filter arrays method (https://www.freecodecamp.org/challenges/filter-arrays-with-filter) with a general expression for all non alphanumeric characters.

For example:

var newArray = oldArray.filter(function(val) {

return val !== /[\W_]/g;

});

Can I do that? In the mozilla guide (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Regular_Expressions) it mentions you can use regular expressions with replace, and I understand how to do that, but it doesn’t mention filter at all.

To put another less abstract example, this is the code I’m working on:

function palindrome(str) {
  
  var splitStr = str.split("");
  
  var filterArray = splitStr.filter(function(val) {
    
    return val !== /[\W_]/g;
  });
  
  return filterArray;
}

palindrome("ey*e");

If I’m doing things right so far, the function should return [“e”, “y”, “e”]. But it returns [“e”, “y”, “*”, “e”] (as if I hadn’t filtered it at all). I just wonder if I’ve made a mistake in my code, or if one simply can’t use filter with regular expressions.

If that's the case, why? Why can't one use filter with regular expressions!? Why do we have to use replace instead?

like image 770
Milena Avatar asked Jun 19 '26 00:06

Milena


1 Answers

This really isn't an issue relating to .filter(), it's just that you aren't testing your string against your regular expression properly.

To test a string against a regular expression you use the .test() method:

function palindrome(str) {
  
  var splitStr = str.split("");
  
  var filterArray = splitStr.filter(function(val) {
    
    // Test the string against the regular expression
    // and test for no match (whole thing is preceeded by !)
    return !/[\W_]/g.test(val);
  });
  
  return filterArray;
}

console.log(palindrome("ey*e"));
like image 91
Scott Marcus Avatar answered Jun 20 '26 14:06

Scott Marcus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!