Regex assistance

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • BaseballGraphs
    New Member
    • Sep 2010
    • 75

    Regex assistance

    I'm trying to extract several portions of a string and am having some issues.

    The string is: "http://www.google.com http://www.yahoo.com http://www.facebook.co m"

    I would like to extract google, yahoo, and facebook from that string.

    I've been trying this:
    Code:
    var string  = "http://www.google.com http://www.yahoo.com http://www.facebook.com";
    var several = string.match( /www.(\w+).com/g );
    console.log( several );
    This does not seem to be working. Can you please help me out?
    Thanks!
  • johny10151981
    Top Contributor
    • Jan 2010
    • 1059

    #2
    If you are confident enough to read next string of "www." and before next . then do this

    Code:
    <SCRIPT>
    	Query="www.yahoosadf.com";
    	n=Query.indexOf("www.",0)+4;
    	last=Query.indexOf(".",n);
    	document.write(Query.substring(n,last));
    </SCRIPT>

    Comment

    • gits
      Recognized Expert Moderator Expert
      • May 2007
      • 5388

      #3
      you could even extend your regex with more excludes like this:
      Code:
      var s = "http://www.google.com http://www.yahoo.com http://www.facebook.com";
      var m = s.match(/[^www.|^com|^ http:\/\/](\w+)/g);
      console.log(m);

      Comment

      • Mariostg
        Contributor
        • Sep 2010
        • 332

        #4
        Code:
        <script>
        var haystack  = "http://www.google.com http://www.yahoo.com http://www.facebook.com";
        var urls=haystack.split(" ");
        var pattern=/www.(\w+).com/;
        
        for (var i=0; i<urls.length;i++){
            document.write(urls[i].match(pattern)[1]+'<br>');
        }
        </script>
        Outputs:
        google
        yahoo
        facebook

        Comment

        Working...