Javascript 是否从字符串的开头删除特定字符串?
我的代码:Javascript 是否从字符串的开头删除特定字符串?,javascript,jquery,string,replace,match,Javascript,Jquery,String,Replace,Match,我的代码: 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); 输
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 is not defined
您需要在JavaScript中使用.replace()
,preg\u replace()
用于PHP
试试这个:
pathname = pathname.replace(string, '')
您需要在JavaScript中使用.replace()
,preg\u replace()
用于PHP
试试这个:
pathname = pathname.replace(string, '')
您需要删除正则表达式周围的引号
var pathname=“/removethis/page/removethis/color.html”;
//路径名的输出为“/removethis/page/removethis/color.html”
var regex=/^\/removethis/;
if(路径名匹配(正则表达式)){
pathname=pathname.replace(正则表达式“”);
}
警报(路径名)代码>您需要删除正则表达式周围的引号
var pathname=“/removethis/page/removethis/color.html”;
//路径名的输出为“/removethis/page/removethis/color.html”
var regex=/^\/removethis/;
if(路径名匹配(正则表达式)){
pathname=pathname.replace(正则表达式“”);
}
警报(路径名)代码>您可以使用一次性完成此操作
var pathname=“/removethis/page/removethis/color.html”;
var string=“/removethis/”;
var regex=new RegExp(“^”+字符串);
console.log(路径名.replace(regex)(“”))代码>您可以使用一次性完成此操作
var pathname=“/removethis/page/removethis/color.html”;
var string=“/removethis/”;
var regex=new RegExp(“^”+字符串);
console.log(路径名.replace(regex)(“”))
preg_replace
是一个PHP函数。在JavaScript中,需要string.replace(regex,replacement)
preg_replace()
是一个PHP函数,而不是JS。为了在JS中使用它,我现在做了这个pathname=pathname.replace(string,pathname)但是现在输出是/removethis/page/removethis/color.html
preg\u replace
是一个PHP函数。在JavaScript中,需要string.replace(regex,replacement)
preg_replace()
是一个PHP函数,而不是JS。为了在JS中使用它,我现在做了这个pathname=pathname.replace(string,pathname)
但是现在输出是/removethis/page/removethis/color.html
是的,这很有效!是的,这很有效!这是可行的,但是为什么RegExp比replace `@fala更好呢?好吧,反正你需要regex,因为你正在用^
-检查字符串的开头,所以最好使用regex.replace一次性完成,而不是先进行regex.match,然后进行字符串替换。这是可行的,但是为什么RegExp比replace `@fala更好呢?好吧,反正你需要regex,因为您正在使用^
-检查字符串的开头,所以最好使用regex.replace一次性执行,而不是先执行regex.match,然后执行字符串替换。