1

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!

Dshiz
  • 3,099
  • 3
  • 26
  • 53

2 Answers2

3

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.

Kyle Becker
  • 1,360
  • 12
  • 20
0
var urlParam = location.search.split("var=")[1];

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

urlParam = urlParam.replace(/(\?|=)/g, function (matched) {
  return mapObj[matched];
});
linktoahref
  • 7,812
  • 3
  • 29
  • 51