将字符串插入 url 并重定向

Insert string to url and redirect

是否可以在 url 中插入一个字符串? 假设我想要 www.domain.com/news 在 com 和 news

之间插入语言标志 de

您可以使用 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 字符串,或者您知道基础 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);