【问题标题】:Remove a specific string from the beginning of a string? [closed]从字符串的开头删除特定字符串? [关闭]
【发布时间】:2020-01-23 09:10:55
【问题描述】:

我的代码:

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

【问题讨论】:

  • preg_replace 是一个 PHP 函数。在 JavaScript 中,您需要 string.replace(regex, replacement);
  • preg_replace() 是 PHP 函数,而不是 JS。要在 JS 中完成这项工作,请使用 replace()
  • 我现在这样做了pathname = pathname.replace(string, pathname);,但现在输出是/removethis/page/removethis/color.html

标签: javascript jquery string replace match


【解决方案1】:

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

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

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

【讨论】:

  • 这行得通,但为什么 RegExp 更好的替换`
  • @fala 好吧,无论如何您都需要正则表达式,因为您正在使用 ^ 检查字符串的开头 - 所以不妨使用 regex.replace 一次性完成,而不是执行regex.match 然后一个字符串替换。
【解决方案2】:

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

试试这个:

pathname = pathname.replace(string, '')

【讨论】:

  • 是的,这行得通!
【解决方案3】:

您需要从您的正则表达式中删除引号。

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-01-28
    • 2018-12-22
    • 1970-01-01
    • 2022-11-28
    • 2017-01-23
    • 1970-01-01
    • 2020-04-16
    相关资源
    最近更新 更多