【发布时间】:2020-01-23 09:10:55
【问题描述】:
我的代码:
var pathname = window.location.pathname;
//output of pathname is "/removethis/page/removethis/color.html"
var string = "/removethis/";
if (pathname.match("^"+string)) {
pathname = preg_replace(string, '', pathname);
}
alert(pathname);
输出是:
我尝试找出字符串的开头是否与/something/ 匹配,如果是,则从"pathname"; 的开头删除此字符串
我的期望是:
page/removethis/color.html
但我得到了错误
preg_replace is not defined
【问题讨论】:
-
preg_replace是一个 PHP 函数。在 JavaScript 中,您需要string.replace(regex, replacement); -
preg_replace()是 PHP 函数,而不是 JS。要在 JS 中完成这项工作,请使用replace() -
我现在这样做了
pathname = pathname.replace(string, pathname);,但现在输出是/removethis/page/removethis/color.html
标签: javascript jquery string replace match