【发布时间】:2018-11-06 01:36:03
【问题描述】:
是否可以在 url 中插入字符串?
假设我希望 www.domain.com/news 在 com 和 news 之间插入语言标志 de
【问题讨论】:
-
有趣!不努力尝试,没有代码,但投票!
标签: javascript jquery url href location-href
是否可以在 url 中插入字符串?
假设我希望 www.domain.com/news 在 com 和 news 之间插入语言标志 de
【问题讨论】:
标签: javascript jquery url href location-href
如果您有一个包含协议的完整 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);
【讨论】:
http://www.example.com/news/some/blah/blah
/ 的索引或尝试拆分并自己加入它们
您可以使用indexOf 查找/ 字符位置,并使用slice 和join 将字符串分解为一个数组并在将第二个字符串插入该位置时重构它:
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);
【讨论】: