【问题标题】:how to remove the particular string from the url and update it [closed]如何从网址中删除特定字符串并更新它[关闭]
【发布时间】:2019-03-12 14:37:42
【问题描述】:

我想从 url 中删除字符串并在删除后更新。

示例:www.abc.com/xyz

我需要删除 xyz 并将其更新为 www.abc.com

谢谢

【问题讨论】:

  • 您自己尝试过什么解决方法?
  • 尝试浏览器位置 api,它有 location.hostname 属性,将返回名称
  • wdym “更新它”?
  • 按照上面给出的链接,然后window.location.href = /* your link here */; 更新您的浏览器。

标签: javascript jquery


【解决方案1】:

可以使用js拆分方法https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/split

var url = 'www.abc.com/xyz';
var arr = url.split('/');
var newUrl = arr[0];
console.log(newUrl);

/*if string the url is 'www.abc.com/xyz/pqr' and you want only 'www.abc.com/xyz' thn?*/

var url = 'www.abc.com/xyz/pqr';
var arr = url.split('/');
if(arr.length > 1){
	arr.pop();
}
var newUrl = arr.join('/');

console.log(newUrl);

【讨论】:

  • 如果字符串的 url 是 'www.abc.com/xyz/pqr' 我只想要 'www.abc.com/xyz' 吗?
  • 感谢您的评论。我已根据您的新 url 字符串添加了新代码。你也可以使用 js pop 和 join 方法
【解决方案2】:

const url = new URL("https://example.com/test")
url.pathname = "/"

console.log(url.toString())

【讨论】:

  • 此功能在 Web Workers 中可用。
猜你喜欢
  • 2016-06-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-28
  • 1970-01-01
  • 1970-01-01
  • 2021-03-17
  • 1970-01-01
相关资源
最近更新 更多