Home > OS >  Regex to convert URL to string
Regex to convert URL to string

Time:09-21

REGEX ONLY

I exclusively need Javascript regex code to convert URLs like

https://hello.romeo-juliet.fr
https://hello.romeojuliet.co.uk 
https://hello.romeo-jul-iet.fr 
https://hello.romeo-juliet.com

into this string romeojuliet

Basically want to get the alphabetic domain name with removing all other characters and https://, com/co.uk/fr etc Top Level Domains

Would be helpful if done using JS replace. I tried till here

let url="https://hello.romeo-juliet.fr";
const test=url.replace(/(^\w :|^)\/\/(\w .)/, '');
console.log(test);

CodePudding user response:

A non regex solution:

Get the host of the URL (by parsing the string with the URL() constructor and getting its host property), split by a period and get the second item in the resulting array, then remove all occurences of -:

let url="https://hello.romeo-juliet.fr";
const test = new URL(url).host.split(".")[1].replaceAll("-", '');
console.log(test);

CodePudding user response:

You can use it with no regex as the following:

let url="https://hello.romeo-juliet.fr";
url.substring(url.indexOf(".") 1, url.lastIndexOf("."));
// result: romeo-juliet

I hope this answers your question

  • Related