0

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!

Joe Torraca
  • 1,949
  • 5
  • 31
  • 50

2 Answers2

1

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:

Community
  • 1
  • 1
icyrock.com
  • 27,952
  • 4
  • 66
  • 85
  • Thanks this looks like it will work. Forgot about using regex. – Joe Torraca Feb 21 '12 at 03:03
  • Actually, Im an idiot, I forgot that this is what my search looks like `/search/option1/Query Here/` and `/search/option2/Query Here/`. How can I check `if m[1] == '/search/option1/'`. I'm not good at regex at all so I couldn't even think where to begin with this. Thanks! – Joe Torraca Feb 21 '12 at 03:10
  • No worries, just use this regex instead: /(.*\/#!\/search\/[^\/]+\/)([^\/]+)/. This will catch anything after search and the next slash (e.g. `/search/abc/Query Here/` or `/search/hi-there-cute-bunny/Query Here/` or things like that). Updated jsFiddle you can play with: http://jsfiddle.net/zSBkL/2/ – icyrock.com Feb 21 '12 at 03:47
0

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 ).

Beetroot-Beetroot
  • 18,022
  • 3
  • 37
  • 44