简体   繁体   中英

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.

截图与描述

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!

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);
}

这个正则表达式将匹配搜索参数之后的任何内容,这是您正在寻找的吗?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM