等效的 JavaScript substr_count?
我正在尝试为 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 中执行同样的语句呢?
谢谢你们!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
JavaScript 中的 Substr_count 也可以实现如下:
Substr_count in JavaScript can also be implemented as follows:
你实际上是要计算子字符串的数量还是只是看看它是否存在?如果是第一个,则使用 Frosty Z 的答案,如果是后者,则首先不应在 PHP 中使用
substr_count
,而应使用strpos
(它可能更快) )。后者的 JS 版本是 String 方法
indexOf
:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/indexOf
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, butstrpos
instead (it's probably faster).The JS version of the latter is the String method
indexOf
:https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/String/indexOf
请检查 http://locutus.io/php/substr_count/ 以获得等效内容。
Please check http://locutus.io/php/substr_count/ for the equivalent.