Skip to content
Advertisement

Regex to consolidate multiple rules

I’m looking at optimising my string manipulation code and consolidating all of my replaceAll‘s to just one pattern if possible

Rules

  • strip all special chars except -
  • replace space with -
  • condense consecutive - ‘s to just one -
  • Remove leading and trailing -‘s

My code

JavaScript

Does the job but obviously looks shoddy.

My test assertions –

JavaScript

Advertisement

Answer

Disclaimer: I don’t think a regex approach to this problem is wrong, or that this is an objectively better approach. I am merely presenting an alternative approach as food for thought.

I have a tendency against regex approaches to problems where you have to ask how to solve with regex, because that implies you’re going to struggle to maintain that solution in the future. There is an opacity to regexes where “just do this” is obvious, when you know just to do this.

Some problems typically solved with regex, like this one, can be solved using imperative code. It tends to be more verbose, but it uses simple, apparent, code constructs; it’s easier to debug; and can be faster because it doesn’t involve the full “machinery” of the regex engine.


JavaScript

(This code is wildly over-commented, for the purpose of explaining it in this answer. Strip out the comments and unnecessary things like the else, it’s actually not super complicated).

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement