2

I need to make a function in JavaScript to locate href inside the url that is given, and to return it as a string.

For example: http://stackoverflow.com/

So the function starts with: function example(url) {}
I want to find the first link inside this url that contain the words google.

In this page there is somewhere link like <a href:"http://google.com/asdasdadsa/asdada">
The function is to return the whole link as string.

4
  • I'm confused. Are the url's like this? http://example.com?param1=abc&param2=d&...http%3A//www.google.com" Commented May 30, 2013 at 3:21
  • I think you mean "you want to find the first href from a set of links on a page that contains the words "google"? Commented May 30, 2013 at 3:23
  • No, the url is inside the source code of example.com, like a link somewhere in the website. Thank's for the fast respond. Commented May 30, 2013 at 3:25
  • David, yes its exactly what I mean. Commented May 30, 2013 at 3:26

1 Answer 1

3

So basically from what I can gather, you want to look at each link on the page and get the whole URL if it includes some string (i.e. google).

Here's a function that finds the first link matching a certain string:

function checkLinks( searchString ) {
    var url;

    // Go through each link
    $('a').each( function ( ) { 

        // Check if the search string exists
        if(  $(this).attr('href').indexOf(searchString) != -1 ) { 
            url = $(this).attr('href');
            // If we've found one, stop the each. 
            return false;
        }
    });
    return url;
}

I've put together a jsfiddle showing an example of how this function could be used:

http://jsfiddle.net/K9KvS/1/

EDIT:

I've just seen you need to do this on a remote URL. You probably need to use AJAX to load in the code, then run this on the code you have. Unfortunately due to the same origin policy, you can't get this directly, so you'll need to run a server-side script on your server (e.g. using PHP) to load the content of the external page, then an AJAX call from your JS to pull it into your javascript.

Modified version to include an AJAX load of some code, then a find on that code:

// Create a function to do the actual search
function checkLinks( code, searchString ) {
    var url;
    // Search the code for all <a> tags, the loop over them
    $(code).find('a').each( function ( ) {

        // Check if there is a match (indexOf returns -1 if not)
        if(  $(this).attr('href').indexOf(searchString) != -1 ) {

            // set the "url" variable to the href
            url = $(this).attr('href');
            // Stop looping
            return false;

        }
    });
    return url;
}

// Now, when the page loads, attach an AJAX call to a button with ID "linkchecker"
$( function ( ) {
    $('#linkchecker').click( function( ) {
        var code;

        // Perform the AJAX call, load the data and call our function above to find "google.com"
        $.get( 'load_code.php?url=http://www.google.com', function( data ) {
            code = data;
            alert( checkLinks( code, 'google.com' ) );
        });
    });
});

load_code.php would probably look something like this (probably with some error checking, etc):

<?php
    $htm = file_get_contents($_GET['url']);
    echo $htm;
?>

Update: Using Raw Javascript

We'll modify checkLinks from above to use raw Javascript:

function checkLinks( code, searchString )
{

    var url;

    // We need to create an HTML document element so we can use javascript dom functions on it.
    var doc = document.createElement("html");
    doc.innerHTML = code; // put the code into the document

    // Get all  links in the code
    var links = doc.getElementsByTagName("a")

    // Loop over all links
    for (var i=0; i<links.length; i++) {
        // Check if the search string (e.g "google.com") is found in the href of the link
        if(  links[i].getAttribute("href").indexOf(searchString) != -1 ) {
            // Set it to the return value
            url = links[i].getAttribute("href");
            // stop looping
            break;
        }
    }

    return url;
}

So firstly, you need to set up the Ajax request object. The problem is this differs between browsers, so you need an unpleasant bit of code to generate it across them. The following is modified from the tiztag ajax tutorial:

function makeAJAXObject(){
    var ajaxRequest;  // The variable that makes Ajax possible!

    try{
        // Opera 8.0+, Firefox, Safari
        ajaxRequest = new XMLHttpRequest();
    } catch (e){
        // Internet Explorer Browsers
        try{
            ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try{
                ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e){
                // Something went wrong
                alert("Your browser broke!");
                return false;
            }
        }
    }
    return ajaxRequest;
}

Ok, so now we've got our AJAX object, we want to get it to load a page, and tell it how to handle what we get back:

/*
 * A function to load a given URL and process the code from it.
 * It takes three arguments:
 *   php_handler   The name of the PHP file that will load the code (or ASP, or whatever you choose to use) 
 *   url           The URL to be loaded.
 *   searchString  The string to find in the links (e.g. "google.com").
 */
function load_page( php_handler, url, searchString )
{
    // Get the ajax object using our function above.
    window.ajax = makeAJAXObject( );

    // Tell the AJAX object what to do when it's loaded the page
    window.ajax.onreadystatechange = function(){
        if(window.ajax.readyState == 4){ // 4 means it's loaded ok.
            // For simplicity, I'll just alert this, but you would put your code to handle what to do when a match is found here.
            alert(checkLinks( window.ajax.responseText, searchString ));    
        }
    }

    // Set up the variables you want to sent to your PHP page (namely, the URL of the page to load)
    var queryString = "?url=" + url;
    // Load the PHP script that opens the page
    window.ajax.open("GET", php_handler + queryString, true);
    window.ajax.send(null); 
}

The final thing is to attach this to a button when the page has loaded:

window.onload = function( ) {
    document.getElementById('linkchecker').onclick = function( ) {
        load_page('load_page.php', 'http://www.example.com', 'google');
    }
}

Please note, there's likely to be built in WinJS functions to handle some of the AJAX stuff, but I've never tried Win 8 app development, so I don't know them!

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

20 Comments

Thank you for your answer, Unfortunately I can't use jquery in the win 8 app development feathers is not including jqurey this one reason why I could't do it, but maybe there is a way to pass that around I will look. Thank you again for your answer.
In which case, you should remove jQuery from the tags :) You can do the same using raw Javascript, see this link for some help: stackoverflow.com/questions/1487588/…
Thank you very much! I working right now to make it raw javascript (not easy for me but I don't complain ), if you could just make a little explanation of the script so I could do it myself next it would be grate ! AND once again THANK YOU !
I've updated it with all the raw JS you'd need and commented it up. If you need any more help, let me know.
n00dle I have no words to tell you how much I am thankful to you, I never thought you will go so far just to help someone, that's just grate ! All I can say is THANK YOU VERY MUCH! I will try it right now .
|

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.