문제

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