0

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 : (/^\//, '')

2 Answers 2

2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Sweet, that helps a lot thanks Sam. I think the escaped / was confusing me
No problem, there are many special characters in regex. If we hadn't escaped the /, Javascript would've thought we had hit the closing delimiter (/^/).
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.