user2044638
user2044638

Reputation: 543

JavaScript - replacement string contains old string and therefore replaces itself

When used in a browser this javascript:

var url = window.location.toString();
window.location = url.replace(/.com/, '.com.nyud.net').replace(/.net/, '.net.nyud.net');

causes this to happen with websites ending with .com (and other TLDs when included):

from

website.com/123

to

website.com.nyud.net.nyud.net/123

while it works correctly with websites ending with .net:

from

website.net/abc

to

website.net.nyud.net/abc

How can I adjust it to make it work correctly?

Upvotes: 0

Views: 373

Answers (3)

gen_Eric
gen_Eric

Reputation: 227310

This happening because the .net in .com.nyud.net is being replaced with .com.nyud.net.

To fix this, use one regex to replace all the TLDs.

window.location = url.replace(/\.(com|net|org)(?=$|\/|\?)/, '.$1.nyud.net');

I modified the regex a bit, so that it uses backreferences to add the TLD to the replace string. It also makes sure the .com is either followed by the end of the string or a /, so it doesn't match things like www.company.net.

UPDATE: Fixed to replace URLs like website.com/123 correctly.

Upvotes: 4

Robin van Baalen
Robin van Baalen

Reputation: 3651

You should probably use the $ in your regular expression to define that you're replacing the end of a string instead of just any piece of the string.

Then format the host instead of the full url and add anything after the / afterwards.

Something like this:

var host = window.location.host; // website.com
var restOfUrl = window.location.pathname;

var newHost = host.replace(/\.com$/, '.com.nyud.net').replace(/\.net$/, '.net.nyud.net');
var url = newHost + restOfUrl;

Upvotes: 0

pgreen2
pgreen2

Reputation: 3651

The first replace replace .com with .com.nyud.net. The second replace then replaced the new .net with .net.nyud.net. So you end up with website.com.nyud.net.nyud.net

Flip the logic so that .net is replaced before .com.

Use url.replace(/.net/, '.net.nyud.net').replace(/.com/, '.com.nyud.net'); instead.

Update: Escape . because it is special. url.replace(/\.net/, '.net.nyud.net').replace(/\.com/, '.com.nyud.net');

Update: You probably want to only replace at the end of urls: url.replace(/\.net$/, '.net.nyud.net').replace(/\.com$/, '.com.nyud.net'); but that assumes no path.

Upvotes: 1

Related Questions