等价的Javascript substr_count?

问题描述 投票:3回答:3

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

在PHP中我有这个

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

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

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

多谢你们!

javascript string phpjs
3个回答
4
投票

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

后者的JS版本是String方法indexOf

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

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


17
投票

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

var substr_count = hay_stack_string.split('search_substring').length - 1;

3
投票

请检查http://locutus.io/php/substr_count/的等效物。

© www.soinside.com 2019 - 2024. All rights reserved.