Ad

Is There A Way To Condense The Following Regex Replace? (javascript)

- 1 answer

I'm trying to remove the whitespace from the beginning and the end of the input string, replace more than 1 space with just one space and remove all special characters. The snippet (attached herewith) works but I just wanted to ask if there is a way I can make this look slightly less uh... ugly? There must be a better way of writing this, right?

const filterInput = (vals) => {
  console.log(vals.replace(/^(\s*)|(\s*)$/g, '').replace(/\s+/g, ' ').replace(/[^\w ]/g, ""));
};

filterInput(" squid*^%ward     sponge((bob        ")

Ad

Answer

trim() the string first, instead of using the first .replace:

const filterInput = (vals) => {
  const result = vals
    .trim()
    .replace(/\s+/g, ' ')
    .replace(/[^\w ]/g, '');
  console.log(result);
};

filterInput(" squid*^%ward     sponge((bob        ")

You could reduce it into a single regular expression, but that wouldn't be as readable IMO:

const filterInput = (vals) => {
  const result = vals
    .trim()
    .replace(/\s+|\W/g, s => s[0] === ' ' ? ' ' : '');
  console.log(result);
};

filterInput(" squid*^%ward     sponge((bob        ")

Ad
source: stackoverflow.com
Ad