Nathan
Nathan

Reputation: 12010

How to get search query from the hash in the URL

I am adding a Search feature, and if the user is on the search results and they refresh the page I want it to stay at that search. I already put the search query into the URL, but I don't know how to retrieve it. It will most likely require a regexp so anyone that is experienced with regexp, please help.

screenshot w/ description

Here is how I put it into the URL:

function trimspace(str) {
    str = str.replace(/ +(?= )/g, '');
    return str;
}
function searchMail() {
    var query = trimspace($('#search_input').val());
    if (query == '' || !query || query == null) {
        $('#search_input').focus();
    }
    else {
        window.location.hash = '#!/search/' + query;
        $('#loader').show();
        $.get('tools.php?type=search', { q: query }, function(data, textStatus) {
            $('#loader').hide();
            if (textStatus == 'success') {
                hideAllTabs();
                $('#search_results').html(data).show();
                document.title = "Search results - WeeBuild Mail";
            }
            else {
                alertBox('Search failed. Please try again in a few minutes.', 2500);
            }
        });
    }
}

And besides just retreiving the query I need to be able to detect if the hash is #!/search/query.

Thanks in advance!

Upvotes: 1

Views: 3164

Answers (3)

Augustus Kling
Augustus Kling

Reputation: 3333

Detect if query is #!/search/query:

location.hash==='#!/search/query'

Finding out about the query parts assuming the query is #!/search/query:

var parts = location.hash.split('/');

parts[0] is #!. parts[1] is search and parts[2] is test. Doing with the parts want you want should now be trivial enough.

In response to the comments:

function getPartAndRemainder(){
    var parts = location.hash.split('/');
    if(parts[0]!=='#!' || parts.length<2){
        // Value after # does not follow the expected pattern #!/part/any_parameters
        throw new Error('Cannot parse application part.');
    }
    return {
        // Contains the part of your application (word after first slash after #)
        part: parts[1],
        // Contains everything after second slash after # or the empty string
        remainder: location.hash.substring(
            // Length of #! (or whatever somebody might use instead)
            parts[0].length
            // Length of first slash
            +1
            // Length of your application part's name
            +parts[1].length
            // Length of the second slash
            +1)
    };
}

The function gives back an object that contains the part of your application at the key part and the remainder key will contain the rest. So, if your URI would be something#!/search/test the function would return {part:'search', remainder:'test'}. In case the URI can't be parsed, you'll get an error and you should then use a sensible default instead.

You would use the method as follows whenever the hash changes or at some other event (point in time) where you are interested in the hash value:

try {
    var hashValue = getPartAndRemainder();
    if(hashValue.part==='search'){
        var query = hashValue.remainder;
        alert('You searched: '+query)
    }
    if(hashValue.part==='inbox'){
        alert('You are in inbox, now');
    }
} catch(e){
    // It was not possible to parse the value after the # from URI according to our expected pattern.
    alert('No idea what to do with: '+location.hash);
}

Upvotes: 3

slier
slier

Reputation: 6750

var match = /\/.*\/.*\/(.*)\//i.exec(location.hash)
//match contain the query

Upvotes: 0

Ian Jamieson
Ian Jamieson

Reputation: 4816

This regex will match anything after the search param, is this what you are looking for?

/#1/search/(.*)/

Upvotes: 1

Related Questions