Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Can someone explain this regex for me?

It is a regex used in a jquery function on location.pathname.replace(/^\//,'')

What does it actually mean. Cheers :)

1 Answer

/ ^ assert position at start of the string \/ matches the character "/" literally /, Change it to '' nothing. In other words - erase / at the begging of the location.pathname string.

You can try it here: https://regex101.com/

Ah. Now that is the part that was confusing me. So \/ is an opperator in itself or is it making sure that the / char is escaped? and the final; / is just depicting the end of the string?

So how does it know to turn that in to ''? Is this just how they work with anything after the comma or does that section also mean something in the redex?

I'm guessing this is part of the 'replace' function, not the regex... >.>

.replace() is a method of strings in JS. .replacet() take two parameters — regular expression inside /../ then "," which is separate arguments of any js method and the replacement part.

For example:

var name = "Sasha Grey an actress indeed";
var otherName = name.replace(/Sasha Grey/, "Peter Norton")

console.log(otherName); // Peter Norton an actress indeed

More about Regular Expression you can read here.

Great resource man. Greatly appreciated (Y)