Is it possible to insert a stringi into url?
Lets say I want www.domain.com/news
to insert language flag de
between com and news
Asked
Active
Viewed 1,468 times
2

Damian Doman
- 522
- 8
- 19
-
Interesting! no effort try, no code but up vote ! – Pedram May 27 '18 at 07:11
2 Answers
3
You can use indexOf
to find the /
character position, and slice
with join
to break the string into an array and reconstruct it while inserting the 2nd string into this position:
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);

Koby Douek
- 16,156
- 19
- 74
- 103
-
That's what I needed, now in case of redirecting, just use window location with new url variable right? – Damian Doman May 27 '18 at 07:17
3
If you have a full url string that includes protocol or you know the base url or if this is all based on current location
you can use the 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);

charlietfl
- 170,828
- 13
- 121
- 150
-
I believe this answer should mark as accepted, because it makes sense, it work even URL is `http://www.example.com/news/some/blah/blah` – Pedram May 27 '18 at 07:25
-
@Pedram right...no need to figure out index of `/` or try splitting things up and joining them yourself – charlietfl May 27 '18 at 07:27