简体   繁体   中英

Pass url parameter without question mark and equal sign?

I'm using javascript to retrieve a url parameter from the browser and pass it to a server running sockets.io. It's working exactly as intended, but I would like to grab the parameter without requiring the question mark or equal sign.

Instead of /?var= I would like it to be: /var- or /var_ , etc.

Is there a good way to accomplish this without server-side URL rewriting?

Current code:

var urlParam = location.search.split("var=")[1]; // get the url parameter http://localhost/?var=[some url parameter value]

if (urlParam == null) {  
    socket.emit('newRoom'); 
} else { 
    socket.emit('urlParam', urlParam); 
}

Thanks!

Certainly possible to grab the url.

window.location.href returns the full path of the url. You can split it using .split('/')

So windows.location.href.split('/') will give you an array of strings where each element is a different part of the url. For example running it on example.com/page/var1/var2 would give you an array ["example.com", "page", "var1", "var2"].

Keep in mind that your server is still going to need to know how to rout requests to example.com/page/var1/var2. So if var1 and var2 are variables for example.com/page, your sever somehow needs to know to serve example.com/page.

var urlParam = location.search.split("var=")[1];

var mapObj = {
   "?":"",
   "=":"-"
};

urlParam = urlParam.replace(/(\?|=)/g, function (matched) {
  return mapObj[matched];
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM