Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I extract text from the middle of a string with Javascript?

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"

like image 937
Samantha J T Star Avatar asked Jul 07 '15 07:07

Samantha J T Star


3 Answers

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

like image 119
Tushar Avatar answered Nov 07 '22 09:11

Tushar


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.

like image 21
tobyUCT Avatar answered Nov 07 '22 10:11

tobyUCT


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

like image 38
alberto-bottarini Avatar answered Nov 07 '22 09:11

alberto-bottarini