Skip to content
Advertisement

Javascript/Angular: Where to put small helper functions

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?

Advertisement

Answer

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

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