2

Sorry for asking simple questions. I have url with like this :

http://sub.maindomain/page/title

I want to add

/en/

in the middle of my url so it will be change to

http://sub.maindomain/en/page/title

thank you for your help

2

5 Answers 5

1

var str='http://sub.maindomain/page/title';
var en='en/';
var position= str.indexOf('page')
alert(str.substr(0, position) + en + str.substr(position));

i guess there will be always page in that url so i found it's index,

and added en before it's index

Sign up to request clarification or add additional context in comments.

Comments

1

If you want to change the actual URL with a new URL parameter en in the address bar. You can try this.

var newUrl = location.origin + '/en' + location.pathname
document.location.href = newUrl

Comments

0

Supposing you're in a context where document is available (since your post is taggued jQuery, it's most likely the case):

const href = 'http://sub.maindomain/page/title?foo=bar#hash';

// Build a link element
const link = document.createElement('a');
link.href = href;

// Add '/en' before its pathname
const result = link.protocol + '//' + link.host + '/en' + link.pathname + link.search + link.hash;

console.log(result);

Comments

0

in case if page is not on after domain some other string is there then try below code.

var str = 'http://sub.maindomain/page/title';
var arr = str.split(/\//);
arr.splice(3, 0, 'en');
str = arr.join('/');

Comments

0

let url = "http://sub.maindomain/page/title";
let textToAdd = "en/";
//Split the url string into array of two elements and then join them together with a new string 'en/page' as a separator
let newUrl = url.split('page').join(`${textToAdd}page`);
console.log(newUrl);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.