Вопрос

Hi I have been dissecting my friends code and I am really confused about how the regular expression he used works. I'd really like to understand what each component of his expression is doing.

I console.log the function and see the output, but I want to know HOW the regex gathers the outcome.

Here is the part of the function that has the regex in it:

location.pathname.replace(/^\//, '') == this.pathname.replace(/^\//, '') 

Really I'd just like to know the role of each character in the regex : (/^\//, '')

Это было полезно?

Решение

Here is a quick explanation of the expression:

/      # Starting delimiter (so Javascript knows this is a regular expression)
 ^     # Match the start of the string
 \/    # Match a / (needs to be escaped with \)
/      # Ending delimiter

As for the .replace() function, it takes the string (location.pathname) and replaces the first parameter (either a string or regular expression) with the second parameter (either a string or a callback function returning a string). This means the backslash at the very beginning of location.pathname will be replaced with a blank string.

Другие советы

The regex needs to be defined between / characters, ^ means "begins with" and / needs to be escaped, hence the \ in front of it. So that is removing the first / in pathname

Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top