是否可以将stringi插入url?
假设我希望www.domain.com/news
在com和news之间插入语言标记de
答案 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);