7

I am trying to find an equivalent function for Javascript. What I am trying to do is look for the current URL and if it has the following first part of the URL then do something.

In PHP I have this

if (substr_count($current_url, $root . $_SERVER['SERVER_NAME'] . '/shop/shop-gallery') {
 doSomething();
}

So as long as it matches that URL and all sub URLs like /shop/shop-gallery/product1..etc, the statement will be true.

Now how can I execute the same exact statement in javascript?

Thanks guys!

Brett Zamir
  • 14,034
  • 6
  • 54
  • 77

3 Answers3

26

Substr_count in JavaScript can also be implemented as follows:

var substr_count = hay_stack_string.split('search_substring').length - 1;
GeekTantra
  • 11,580
  • 6
  • 41
  • 55
5

You you actually what to count the substrings or just see if it's there? If it's the first, then use Frosty Z's answer, if it's the latter you shouldn't be using substr_count in PHP in the first place, but strpos instead (it's probably faster).

The JS version of the latter is the String method indexOf:

if (stringToSearch.indexOf(current_url) > -1)  {
   doSomething();
}

https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/indexOf

RoToRa
  • 37,635
  • 12
  • 69
  • 105
  • Err... Maybe `strpos` instead of `substr` ? Anyway, I think that your answer is more appropriate since Rick wants to check if the URL "begins with" something. – Maxime Pacary Oct 27 '10 at 15:44
  • I am trying to say return true if it matches /site/shop-gallery or /site/shop-gallery/anything after this. –  Oct 27 '10 at 15:54
  • @Frosty Oops, thinking one thing, writing another. Thanks. – RoToRa Oct 27 '10 at 15:59
  • @Rick: Yes, that is why `strpos` is more appropriate that `substr_count`, because you don't actually want to **count**. (`substr` was a typo) – RoToRa Oct 27 '10 at 16:02
  • thank you for the answer thus far but I wrote if(current_url.indexOf("shop-gallery") { doSomething(); } this always true... –  Oct 27 '10 at 16:03
  • ok i revised it to if(current_url.indexOf("shop-gallery") != -1) { doSomething(); } that seemed to work... –  Oct 27 '10 at 16:08
4

Please check http://locutus.io/php/substr_count/ for the equivalent.

DUzun
  • 1,693
  • 17
  • 15
Maxime Pacary
  • 22,336
  • 11
  • 85
  • 113