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

问题描述 投票:1回答:3

我的代码:

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 jquery string replace match
3个回答
1
投票

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

尝试一下:

pathname = pathname.replace(string, '')

1
投票

您可以使用RegExp一次完成此操作

RegExp

0
投票

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

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

var string = "/removethis/";
var regex = new RegExp("^" + string);
console.log(pathname.replace(regex,""));
© www.soinside.com 2019 - 2024. All rights reserved.