5

I have these strings:

baseUrl = "http://www.example.com"
baseUrl = "https://secure.example-server.com:443"

Can someone tell me how I can extract the server information from baseUrl so I can get either "example" and "example-server"

Tushar
  • 85,780
  • 21
  • 159
  • 179
Samantha J T Star
  • 30,952
  • 84
  • 245
  • 427
  • 2
    possible duplicate of [How do I parse a URL into hostname and path in javascript?](http://stackoverflow.com/questions/736513/how-do-i-parse-a-url-into-hostname-and-path-in-javascript) – Panther Jul 07 '15 at 07:41
  • Regex. Just a regex. – briosheje Jul 07 '15 at 07:41
  • [Posible Duplicate] here [http://stackoverflow.com/questions/8498592/extract-root-domain-name-from-string](http://stackoverflow.com/questions/8498592/extract-root-domain-name-from-string). Hope this helps. – hungndv Jul 07 '15 at 07:42

5 Answers5

14

You can use regex:

baseUrl.match(/\.(.*?)\.co/i)[1];

Regex Explanation

  1. /: Delimiters of regex
  2. \.: Matches . literal(need to be escaped)
  3. (): Capturing group
  4. .*?: Match any string
  5. co: Matches string co
  6. i: Match in-case-sensitive
  7. [1]: Get the capturing group

Regex Visualization

enter image description here

Tushar
  • 85,780
  • 21
  • 159
  • 179
2

You can split strings at certain chars with split("."); (see http://www.w3schools.com/jsref/jsref_split.asp) then you can compare the results to your predefined words.

or you take the 2nd element of the results which would usually(?) be what you are looking for.

tobyUCT
  • 137
  • 9
1

Take a look to this free library: http://medialize.github.io/URI.js/.

alberto-bottarini
  • 1,213
  • 9
  • 21
1

If you just want to extract string between two '.'s (or Domain name in URL), you can try this:

var firstDotPos = baseUrl.indexOf(".");
var secondDotPos = baseUrl.indexOf(".",firstDotPos);
var yourString = baseUrl.substring(firstDotPos + 1, 18);
console.log(yourString )
Yurets
  • 3,999
  • 17
  • 54
  • 74
Sabith
  • 1,628
  • 2
  • 20
  • 38
0

You can split it into an array with split() and extract the required one with slice() as follows:

Input

baseUrl = "http://www.example.com"
baseUrl2 = "https://secure.example-server.com:443"
const base = baseUrl.split(".")
const base2 = baseUrl2.split(".")
console.log("Array1 :: ",base)
console.log("Array2 : ",base2)
console.log(base.slice(-2,-1))
console.log(base2.slice(-2,-1))

Output

Array1 :: ["http://www","example","com"]
Array2 : ["https://secure","example-server","com:443"]
["example"]
["example-server"]
Kate Orlova
  • 3,225
  • 5
  • 11
  • 35
tentamdin
  • 19
  • 2