我的代码:
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 /匹配,如果是,则从”路径名“的开头删除此字符串;
我期望是:
page/removethis/color.html
但是我得到了错误
未定义preg_replace
您需要在JavaScript中使用.replace(),preg_replace()用于PHP。
尝试一下:
pathname = pathname.replace(string, '')
您可以使用RegExp
一次完成此操作
RegExp
您需要删除正则表达式周围的引号。
var pathname = "/removethis/page/removethis/color.html";
var string = "/removethis/";
var regex = new RegExp("^" + string);
console.log(pathname.replace(regex,""));