2

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        ")
nox
  • 346
  • 3
  • 13
  • 1
    This `\s+` to this `' '` does more than that, it replaces all whitespace with a space and is the tail that wags the dog. Otherwise, `[^\w ]+` with nothing is all that's needed. –  Oct 27 '19 at 22:45

1 Answers1

3

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        ")
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
  • Thanks for the prompt response! Is there much of a difference in terms of performance do you think between `trim()` and the first `.replace`? I mean yeah it is certainly more readable with `trim()`. – nox Oct 27 '19 at 22:54
  • For a trivially simple string replacement, performance is never worth worrying about. If you want a script to run faster, run a performance test and check to see which parts are taking up the most CPU time - simple string replacement won't be one of them. I bet `trim` is faster because the interpreter knows that it can look backwards from the end to find what to remove, whereas a regex requires the engine to look through all characters in the string until it's done – CertainPerformance Oct 27 '19 at 23:10