nwtnsqrd
nwtnsqrd

Reputation: 55

Whats the difference between .match("") and .match(/^$/)?

I had a problem where I was checking for empty HTML content within a certain element. When I used

someElement.trim().match("")

I would sometimes get true as a result even though the HTML content was empty. I changed it to

someElement.trim().match(/^$/)

and it now seems to always return the correct boolean value.

What is the difference between the two?

Upvotes: 1

Views: 109

Answers (1)

Nahuel Fouilleul
Nahuel Fouilleul

Reputation: 19315

match('') is the same as match(new RegExp('')) and new RegExp('') returns /(?:)/ which matches an empty string as it is not anchored if a substring matched it returns true. Whereas /^$/ is anchored ^ matches the beginning and $ the end of input.

Other examples:

# true
'hello'.match('h')
'hello'.match('e')

# false
'hello'.match('^e$')

Upvotes: 2

Related Questions