Senthil
Senthil

Reputation: 1101

How to change urlpath in javascript

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      

Upvotes: 1

Views: 73

Answers (1)

Code Maniac
Code Maniac

Reputation: 37765

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)) )

Upvotes: 1

Related Questions