Home > Mobile >  How to remove characters in a string that matches a RegEx while preserving spaces?
How to remove characters in a string that matches a RegEx while preserving spaces?

Time:10-10

I am trying to remove characters from a string so that it will match this RegEx: ^[-a-zA-Z0-9._:,] $. For example:

const input = "test // hello". The expected output would be "test hello". I tried the following:

input.replace(/^[-a-zA-Z0-9._:,] $/g, "")

But this does not seem to work

CodePudding user response:

The example output "hello world" that you give does not match your regex, because the regex does not allow spaces. Assuming you want to keep spaces, use

input.replace(/[^-a-zA-Z0-9._:, ]/g, "")

The negation character ^ must be inside the [...]. The is not needed, because /g already ensures that all matching characters are replaced (that is, removed).

If you also want to condense consecutive spaces into a single space (as implied by your example), use

input.replace(/[^-a-zA-Z0-9._:, ]/g, "").replace(/\s /g, " ")

CodePudding user response:

I like to use the following canonical approach:

var input = "test // hello";
var output = input.replace(/\s*[^-a-zA-Z0-9._:, ] \s*/g, " ").trim()
console.log(output);

The logic here is to target all unwanted characters and their surrounding whitespace. We replace with just a single space. Then we do a trim at the end in case there might be an extra leading/trailing space.

  • Related