Private preferences
These are mostly personal preferences, although there is a slight difference in the possibilities (see the last paragraph for this difference). If you do not want to start benchmarking performance measurement and turn the question into one of the characteristics, these are mostly personal preferences.
I prefer to do:
string.match(/word/)
because I think the code reads how my brain thinks about the operation. I take a string object and look for a specific regular expression in it. It makes sense to me that finding something in a string is a string object method. This reads to me like this:
object.action(tool)
how object-oriented code should work, in my opinion.
If you have:
/word/.match(string)
then it seems to me:
tool.action(object)
which I find much less logical and less object oriented. Yes, /word/ also technically an object, but it is not an object that I am trying to work on, I think it is more like a tool or parameter that I use with my object.
Obviously both work. You can decide what you like.
One significant difference
There are a few things that I believe can only be done on the regular expression object. For example, if you want to match all occurrences of a regular expression, you need to create a regular expression object, pass the parameter "g" to it, and then call re.exec() several times to get each match until exec returns null that no longer indicates matches. I do not think you can do this with string.match() .
source share