Joe Torraca
Joe Torraca

Reputation: 2018

jQuery Wildcard string

I am making an all ajax website including an ajax search. My search, when entered changes the url into this /#!/search/Query Here/. I already am able to detect the /search/ but only if there is no search query and I just enter it directly. If I have a query, my code doesn't process it because it doesn't match. Is there any way for me to detect only the bold /#!/search/ Query Here/. This is my current code:

var oldLoc = window.location.hash.replace(/^#\!/,"");
if (oldLoc == '/search/') {
    $('#reload_section').load('search.php');
    $('.nav_itm.home').removeClass('active');
    $('.nav_itm.account').removeClass('active');
    _currentScreen = 6;
}

So again I can detect it the url and load the search page but if I throw a query in there, the site just loads the home page. How do I separate everything after /search/ into a different string and loose it on the variable oldLoc. Thanks!

Upvotes: 0

Views: 1646

Answers (2)

Beetroot-Beetroot
Beetroot-Beetroot

Reputation: 18078

Regexp seems unnecessary here.

If I understand correctly, and assuming you don't care about the sequence number, then you should be able to use the far more economical indexOf().

javascript:

if (window.location.hash.replace('#','').indexOf('/search/option') == 1 ) {
    ...
}

replace('#','') is necessary as some browsers include '#' in location.hash and some don't. By eliminating '#' if present, you can test indexOf(...) == 1, which is more specific than indexOf(...) > -1 ).

Upvotes: 0

icyrock.com
icyrock.com

Reputation: 28618

You can use regular expressions, something like this (please change to incorporate into your example as needed):

var url = 'http://www.example.com/page/#!/search/Query Here/';
var m = /(.*\/#!\/search\/)([^\/]+)/.exec(url);
if(m) {
  $('#msgs').text('match: ' + m[1] + ' ----- ' + m[2]);
} else {
  $('#msgs').text('no match');    
}     

See this jsFiddle for a working example which you can use for testing:

See these for more information on the above:

Upvotes: 1

Related Questions