Reputation: 27235
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';
}
}
Upvotes: 2
Views: 6660
Reputation: 20883
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 dev
something.
, 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.
Upvotes: 7
Reputation: 7947
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 + '.' : '';
});
Upvotes: 2
Reputation: 22692
It's hard to tell what you're asking for...
But... based on your sample input/output you could do the following:
No need for regex if that's actually what you want:
function trimInput(s) {
var n = s.indexOf('.');
if (n === -1) {
return s;
}
var head = s.substring(0, n);
if (head.indexOf("dev") !== -1) {
return "dev." + s.substring(n);
}
else {
return s.substring(n);
}
}
If that's NOT want you want, please update your question to specify what you do want.
Upvotes: 1