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"

3

5 Answers 5

15

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

Sign up to request clarification or add additional context in comments.

Comments

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.

Comments

1

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

Comments

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 )

Comments

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"]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.