gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-01 06:43:15 24 4
gpt4 key购买 nike

我的代码:

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

最佳答案

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

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

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

关于javascript - 从字符串的开头删除特定字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59874886/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com