从字符串开头删除特定的字符串?

时间:2020-01-23 09:10:55

标签: 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);

输出为:

我尝试找出字符串的开头是否与/something/匹配,如果是,则从"pathname";的开头删除该字符串

我期望的是:

page/removethis/color.html

但是我得到了错误

preg_replace is not defined

3 个答案:

答案 0 :(得分:2)

您需要在JavaScript中使用.replace()preg_replace()用于PHP

尝试一下:

pathname = pathname.replace(string, '')

答案 1 :(得分:2)

您可以使用RegExp一次性完成

var pathname = "/removethis/page/removethis/color.html";

var string = "/removethis/";
var regex = new RegExp("^" + string);
console.log(pathname.replace(regex,""));

答案 2 :(得分:1)

您需要删除正则表达式周围的引号。

var pathname = "/removethis/page/removethis/color.html";
//output of pathname is "/removethis/page/removethis/color.html"


var regex = /^\/removethis/;

if (pathname.match(regex)) {
   pathname = pathname.replace(regex, '');
}

alert(pathname);

相关问题