-2

i have a sting that contains http://example.com/user/9800, i want to be able to get the domain name(http://example.com) from this string regardless of the length of the string. See explanation below

var string  = "http://example.com/user/9800";

or

var string  ="http://www.example.com/user/8399";

new string

var new string = "http://example.com";
iTech
  • 97
  • 2
  • 11
  • 2
    Possible duplicate of [Extract root domain name from string](http://stackoverflow.com/questions/8498592/extract-root-domain-name-from-string) – Black Sheep Jun 18 '16 at 10:20

4 Answers4

2

Here is a rough regex pattern to make this work using js:

var string  = "http://example.com/user/9800";
/*string can be any url*/
var ns=string.replace(/(\w+:\/\/[\w\d\.\:]*)\/(.*)/g,"$1");
alert(ns);
Shrikantha Budya
  • 646
  • 1
  • 4
  • 15
1

Use a simple but general regex to extract a domain name:

/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n]+)/im

You can use it like that:

var domain = url.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n]+)/im);
if (domain) {
    console.log(domain[0]);
}

And an example:

function doMatch() {
  var url = $("#urltext").val();
  var domain = url.match(/^(?:https?:\/\/)?(?:[^@\n]+@)?(?:www\.)?([^:\/\n]+)/im);
  if (domain) {
    alert(domain[0]);
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Enter url here: <input type="text" id="urltext" />
<br/><input type="button" onclick="doMatch()" value="try me!" />
Yotam Salmon
  • 2,400
  • 22
  • 36
0

Use the following regex: /(.+?(?=\/user))/. This will capture everything before /user and then you can use it, by getting the second result (first one is the original string). Check the following snippet:

var re = /(.+?(?=\/user))/; 
var str1 = 'http://example.com/user/9800';
var newstr1 = re.exec(str1)[1];
console.log(newstr1);
var str2  ="http://www.example.com/user/8399";
var newstr2 = re.exec(str2)[1];
console.log(newstr2);
Angelos Chalaris
  • 6,611
  • 8
  • 49
  • 75
0

Use this code :

<html>
    <head>
    </head>
        <body>
            <p id="x"></p>
            <script>
                var x = document.getElementById("x");
                var str = "https://example.com/user/9800";
                var patt = /(http:\/\/|https:\/\/)+.*.com/gmi;
                x.innerHTML = str.match(patt);
            </script>
        </body>
    </html>
Ehsan
  • 12,655
  • 3
  • 25
  • 44