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"
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"
You can use regex
:
baseUrl.match(/\.(.*?)\.co/i)[1];
Regex Explanation
/
: Delimiters of regex
\.
: Matches .
literal(need to be escaped)()
: Capturing group.*?
: Match any stringco
: Matches string co
i
: Match in-case-sensitive[1]
: Get the capturing groupRegex Visualization
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.
Take a look to this free library: http://medialize.github.io/URI.js/.
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 )
You can split it into an array with split()
and extract the required one with slice()
as follows:
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))
Array1 :: ["http://www","example","com"]
Array2 : ["https://secure","example-server","com:443"]
["example"]
["example-server"]