Julian
Julian

Reputation: 1831

Why is the javascript replace throwing an error

I keep getting this error "SyntaxError: syntax error" at the first comma, what should I change to make it work?

if (location.pathname.replace(/^//,'') == this.pathname.replace(/^//,'') && location.hostname == this.hostname)

Upvotes: 0

Views: 995

Answers (3)

Use the RegExp constructor

var regexp = new RegExp("^/", "");
if (location.pathname.replace(regexp,'') == this.pathname.replace(regexp,'') && location.hostname == this.hostname)

or escape character /

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

Upvotes: 0

TankorSmash
TankorSmash

Reputation: 12747

It's the double slashes,

if (location.pathname.replace(/^/,'') == this.pathname.replace(/^/,'') && location.hostname == this.hostname)

Upvotes: 1

Hacknightly
Hacknightly

Reputation: 5144

You need to escape the forward slash in your regex

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

Upvotes: 1

Related Questions