【问题标题】:Insert string to url and redirect将字符串插入 url 并重定向
【发布时间】:2018-11-06 01:36:03
【问题描述】:

是否可以在 url 中插入字符串? 假设我希望 www.domain.com/news 在 com 和 news 之间插入语言标志 de

【问题讨论】:

  • 有趣!不努力尝试,没有代码,但投票!

标签: javascript jquery url href location-href


【解决方案1】:

如果您有一个包含协议的完整 url 字符串,或者您知道基本 url,或者这一切都基于当前的 location,您可以使用 URL API

const url = new URL('http://www.example.com/news');
url.pathname = '/de' + url.pathname;
console.log(url.href);

// using current page `location`
const pageurl = new URL(location.href);
pageurl.pathname = '/foobar' + pageurl.pathname;
console.log(pageurl.href);

【讨论】:

  • 我相信这个答案应该标记为已接受,因为它是有道理的,即使 URL 是 http://www.example.com/news/some/blah/blah
  • @Pedram 对...无需弄清楚/ 的索引或尝试拆分并自己加入它们
【解决方案2】:

您可以使用indexOf 查找/ 字符位置,并使用slicejoin 将字符串分解为一个数组并在将第二个字符串插入该位置时重构它:

var url = 'www.domain.com/news';
var flag= 'de/';

var position = url.indexOf('/') + 1;
url = [url.slice(0, position), flag, url.slice(position)].join('');

console.log(url);

【讨论】:

  • 这就是我所需要的,现在在重定向的情况下,只需使用带有新 url 变量的窗口位置对吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-08-01
  • 1970-01-01
相关资源
最近更新 更多