Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Regex return undefined in a JavaScript String

I have a little code snippet where I use Regular Expressions to rip off punctuation, numbers etc from a string. I am getting undefined along with output of my ripped string. Can someone explain whats happening? Thanks

var regex = /[^a-zA-z\s\.]|_/gi;

function ripPunct(str) {
  if ( str.match(regex) ) {
     
          str = str.replace(regex).replace(/\s+/g, "");
  }
  
  return str;
}

console.log(ripPunct("*@£#[email protected]"));
like image 365
knight Avatar asked May 23 '26 02:05

knight


1 Answers

You should pass a replacement pattern to the first replace method, and also use A-Z, not A-z, in the pattern. Also, there is no point to check for a match before replacing, just use replace directly. Also, it seems the second chained replace is redundant as the first one already removes whitespace (it contains \s). Besides, the |_ alternative is also redundant since the [^a-zA-Z\s.] already matches an underscore as it is not part of the symbols specified by this character class.

var regex = /[^a-zA-Z\s.]/gi;

function ripPunct(str) {
  return str.replace(regex, "");
}

console.log(ripPunct("*@£#[email protected]"));
like image 59
Wiktor Stribiżew Avatar answered May 25 '26 15:05

Wiktor Stribiżew



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!