views:

74

answers:

2

I want to write a jQuery function that will return only a part of a given text. For example, in the text:

http://somesubdomain.somesite.com/

How can I write a function so that it returns the text "somesubdomain"? In other words, I want to "subtract" the text "http://" and ".somesite.com/".

Thanks in advance

A: 

If you are asking for a regex for this then the following (in Perl) should do it, assuming $str contains http://somesubdomain.somesite.com/

$str =~ s/http:\/\/([^.]+)\.somesite\.com\//$1/
print $str;

This prints somesubdomain.

Explanation - The regex captures somesubdomain from the string http://somesubdomain.somesite.com/ into the first back reference and then replaces the entire string with that.

Jasmeet
+1  A: 
function getSubdomain() {
    var re = /http\:\/\/(\w+)\.somesite\.com\//;
    return (re(document.location)[1]);
}
sblom
I'm confused on why this the answer..... it has a param `domainString` that has not even used...
Reigel
Reigel, oops. Fixed.
sblom
Well, the Regex works (I can't figure it out as I just starting to understand the regex concept). One question, though, what is the document.location doing there?
Warrantica
The regex (as explained, albeit briefly, in my answer as well), is a. Matches http://b. Matches as many alpha numeric characters (i.e. [a-zA-Z0-9_]) characters after http:// as it can, so this will match somesubdomain, and remembering it in a backreference. Surrounding regex constructs in parenthesis makes it remember what was mathced. c) Finally it matches somesite.com/The captured text (via backreference) is then being returned. For a good introduction to regular expressions checkout http://www.regular-expressions.info/
Jasmeet
Thanks for the detailed explanation, Jasmeet. So using a regex will create an array, the first one being the full url and the second one being "somesubdomain", but can't the third line just return (re[1]); ?
Warrantica
Line 2 defines the regex, line 3 applies the regex and then returns the captured text.
Jasmeet