Home > Back-end >  How do I clean a javascript string?
How do I clean a javascript string?

Time:10-12

Apologize upfront I am very new at regular expressions and JavaScript. I am trying to "clean" a JS string -- Clean means a string should only contain letters a-z, A-Z and spaces. We can assume that there are no double spaces or line breaks.

    function removeChars(s) {
  let cleanString = s.replace(/[^a-z][^A-Z]/gi, "");
  let numClean = cleanString.replace(/\d /g, "");
  return numClean;
}

My RegEx selects almost all the characters I want but it will not do it for the entire string passed in for some of the test cases. Even with the global flag it seems to stop targeting the characters I want. I am not trying to figure out why it seems to stop selecting the characters I want to filter out example: "0123456789(.) ,|[]{}=@/~;^$'<>?-!*&:#%_"

CodePudding user response:

Try the following let cleanString = s.replace(/[^A-Za-z]/gi, ''); The upper and lowercase letters should be within the same [], as to not match on a sequence of 2 characters, but any 1 character.

CodePudding user response:

You're almost there.

Everything you put within [] is considered a single character so:

  • [^a-z] match a non lowercase character
  • [^A-Z] match a non uppercase character

Currently something like Ag will match but you are looking for single characters to replace.

Therefore you need everything you want to match within one set of [] like [^a-zA-Z ] (this also adds the space you want to allow as I can't see it in your original example.

This should work:

function removeChars(s) {
  return s.replace(/[^a-zA-Z ]/g, "");
}

See here to see it in action.

  • Related