1

I have generated url using javascript, Its working but need to know any alternative method to do.

Replace the particular pathname by referencing the object

var serverobj ={
  "about": "about-us",
  "info": "get-our-information",
  "contact": "contactus"
}

var currenturl = "/en/about" or "/en/contact" or "/en/info-tourspots-cn"

function generateurl(){
   var urlpath =currenturl.split("/")[2] ? obj[currenturl.split("/")[2].replace(/-/g, "")]:'';
 var redirecturl = window.location.origin+"/"+en+"/"+urlpath;
window.location.href=redirecturl ;                          
}

Desired output

// will be /en/about-us for /en/about 

// will be /en/contact for /en/contactus  

// will be /en/get-our-information-tourspots-cn for  /en/info-tourspots-cn      
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
Senthil
  • 961
  • 1
  • 8
  • 21
  • `window.location.origin` isn't compatible with Internet Explorer. See a better way to get the window's origin here (https://stackoverflow.com/questions/22564167/window-location-origin-gives-wrong-value-when-using-ie) – Udo E. Jul 07 '19 at 12:46

1 Answers1

1

You can use following regex with replace

(.*\/)([^-]+)(.*)$

enter image description here

var serverobj ={
  "about": "about-us",
  "info": "get-our-information",
  "contact": "contactus"
}

var currenturl = ["/en/about","/en/contact","/en/info-tourspots-cn"]

function generateurl(url){
  return url.replace(/(.*\/)([^-]+)(.*)$/g, (_, g1, g2, g3 = '') => {
    return g1 + serverobj[g2] + g3 
  })
}

currenturl.forEach(url => console.log(generateurl(url)) )
Code Maniac
  • 37,143
  • 5
  • 39
  • 60
  • @Code Manic thanks for solution, working on multilanguage url but sometimes url is like /en/about-us to /en/li-xi-wo-men in that case that if i use above method it /en/undefined-xi-wo-men – Senthil Jul 08 '19 at 03:09
  • @Code Manic for the url will not be same all time, so should i split with `/` and replace with matching server object.please help. thanks – Senthil Jul 08 '19 at 03:13
  • @Senthil you get `undefined` when you don't have any mapping for particular word, you need to make sure you have mapping for expected words, `/en/li-xi-wo-men` there i am matching `li` and since there's no mapping for `li` in your server object it will be undefined – Code Maniac Jul 08 '19 at 10:53