将字符串插入url并重定向

时间:2018-05-27 06:53:47

标签: javascript jquery url href location-href

是否可以将stringi插入url? 假设我希望www.domain.com/news在com和news之间插入语言标记de

2 个答案:

答案 0 :(得分:3)

您可以使用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);

答案 1 :(得分:3)

如果您有一个包含协议的完整网址字符串,或者您知道基本网址,或者这一切都基于当前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);