等价的Javascript substr_count?

3 javascript string phpjs

我试图找到Javascript的等效函数.我想要做的是查找当前的URL,如果它具有URL的以下第一部分,那么做一些事情.

在PHP中我有这个

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

因此,只要它与该URL和所有子URL(如/shop/shop-gallery/product1..etc)匹配,该语句将为true.

现在我如何在javascript中执行相同的确切语句?

多谢你们!

Gee*_*tra 20

JavaScript中的Substr_count也可以如下实现:

var substr_count = hay_stack_string.split('search_substring').length - 1;
Run Code Online (Sandbox Code Playgroud)


RoT*_*oRa 5

你实际上是什么来计算子串或只是看它是否存在?如果它是第一个,那么使用Frosty Z的答案,如果是后者你不应该首先substr_count在PHP中使用,strpos而是(它可能更快).

后者的JS版本是String方法indexOf:

if (stringToSearch.indexOf(current_url) > -1)  {
   doSomething();
}
Run Code Online (Sandbox Code Playgroud)

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