Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript RegEx replace to conditionally remove part of a string

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:

  • Remove the subdomain from the domain unless the subdomain starts with the characters "dev"
  • If the subdomain starts with "dev", then output "dev.domain.com"
  • Retain any port specified at the end of the domain

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';
  }
}
like image 430
Tauren Avatar asked Apr 13 '26 14:04

Tauren


2 Answers

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.

like image 167
Wiseguy Avatar answered Apr 16 '26 03:04

Wiseguy


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 + '.' : '';
});
like image 38
LoveAndCoding Avatar answered Apr 16 '26 02:04

LoveAndCoding



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!