I'm trying to come up with a Javascript RegEx command that will convert these inputs into the following outputs:
INPUT DESIRED OUTPUT
mydomain.com --> mydomain.com
foo.mydomain.com --> mydomain.com
dev.mydomain.com --> dev.mydomain.com
dev-foo.mydomain.com --> dev.mydomain.com
Here's the rules:
My regex skills are failing me. This is what I have so far:
'mydomain.com'.replace(/^(dev)?(-.*)?(mydomain.com)/,'$1.$3');
// .mydomain.com
'foo.mydomain.com'.replace(/^(dev)?(-.*)?(mydomain.com)/,'$1.$3');
// foo.mydomain.com
'dev-foo.mydomain.com'.replace(/^(dev)?(-.*)?(mydomain.com)/,'$1.$3');
// dev.mydomain.com
'dev.mydomain.com'.replace(/^(dev)?(-.*)?(mydomain.com)/,'$1.$3');
// dev.mydomain.com
The first two fail and the last two work. Any suggestions?
Here's javascript that works, but I was hoping to combine it into a single regex replace command. Note that I also want to retain any port specified at the end of the dmain.
var getHost = function () {
var host = window.location.host;
if (host.substring(0,3) === 'dev') {
return host.replace(/^(dev)?(-.*)?(mydomain\.com.*)/,'$1.$3');
}
else {
return 'mydomain.com';
}
}
Just for the sake of showing that it's possible to do in a single regular expression:
'string'.replace(/(?:(^dev).*(\.)|^.*)(mydomain\.com)/, '$1$2$3');
Working example: http://jsfiddle.net/gz2tX/
Here's the breakdown: It either matches devsomething., or it matches anything. If it matches the pattern containing "dev", $1 will contain "dev" and $2 will contain ".". If it doesn't match the pattern containing "dev", $1 and $2 will be empty. ($3 will contain "mydomain.com" in either case.)
So it's possible, but it's convoluted.
My recommendation is to do something more readable and maintainable than this. The time and pain spent figuring out this line is not worth saving a line or two of code length in my opinion.
You can use a function to modify the values with more control in JS in a replace.
var value = "dev-foo.mydomain.com".replace(/^(dev)?[^\.]+\./, function (match, p1) {
return p1 ? p1 + '.' : '';
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With