Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Regex for finding string after the second occurrence of the character

The problem is to get from the string ‘https://myapp-ui.private.dev.mysubdom.eu’ the substring ‘dev.mysubdom.eu’ without the private.

So, in other words, I want to to get the substring after the occurrence of the second dot, the character ‘.’.

What I tried and works (so the next string after the occurrence of the first dot) : to extract the substring ‘dev.mysubdom.eu’ from ‘https://myapp-ui.private.dev.mysubdom.eu’ with the following portion of code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

function buildApiUrl() {
  const { hostname } = window.location;
  const suffix = hostname.replace(/^([^.])+/, '');

  return `${REACT_APP_API_PREFIX}${suffix || REACT_APP_API_SUFFIX}`;
}

Something else that I tried :

([^.]*).+ gives me ‘https://myapp-ui’ but not the desired outcome.

Any ideas ? Thanks !

>Solution :

you can do like this :

with Regex:

const url = 'https://myapp-ui.private.dev.mysubdom.eu';

// Use a regular expression to match the desired substring
const regex = /(?:[^.]+\.){2}(.+)/;
const match = url.match(regex);

// Extract the desired substring from the match
const desiredSubstring = match ? match[1] : '';
console.log(desiredSubstring)

without Regex:

const url = 'https://myapp-ui.private.dev.mysubdom.eu';

// Find the index of the first dot
const firstDotIndex = url.indexOf('.');

// Find the index of the second dot starting from the position after the first dot
const secondDotIndex = url.indexOf('.', firstDotIndex + 1);

// Extract the substring after the second dot
const desiredSubstring = url.substring(secondDotIndex + 1);

console.log(desiredSubstring);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading