1

I'm working on an angular app, which I kind of inherited. I saw that there was a bug with unescaped regex so I wanted to add a function for escaping regex like so:

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

No big deal, right? But where to put this? The regex is used inside a controller. But does it make sense to have this escapeRegExp function inside the scope like so:

                    $scope.escapeRegExp = function(string) {
                      return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
                    }

I'm a little confused where best to put these little functions. What's the best practice?

2
  • 1
    This seems to me like AngularJS? Commented Jan 5, 2021 at 11:12
  • 1
    You only put things in the $scope if the ui needs to have access to it. If it does, then that's a perfectly fine place to put it. Commented Jan 5, 2021 at 11:20

1 Answer 1

2

If you expect to reuse this piece of code - put it to the separate module (utils/common/shared) as a service

If you expect to use this piece of code only for this controller - extract it to the separate file as a function

Sign up to request clarification or add additional context in comments.

4 Comments

I expect to use this piece of code only inside the controller. Can I just throw the first version (without $scope) inside the controller definition and call it a day, or is it better to define the function somewhere else?
From my experience, if you are dealing with regex (or math operations) it's much better to keep them separate and heavily cover with tests. Regexes are really fragile and subject to change. This approach will save you from bugs when requirements will change.
I agree with you about keeping things separate, but it's a huge project and I just want to fix this one bug where regex is not escaped properly before executing a match. Therefore I want to add this one-liner in order to escape a string. From that the question arose where to put such tiny one-liners in angularjs/javascript. So it is fine, to just have a non-scope helper-function inside the controller definition, I assume?
I would say it's OK

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.