3

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]"));

1 Answer 1

3

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]"));

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

1 Comment

Thanks, really helped. Thumbs up

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.