Express.JS - Dynamic Route Alias - regex

I am designing a community site that will allow users to login and befriend others, and their account will be accessible via the following routes:
https://domain.com/en/community/id/:userid AND
https://domain.com/en/community/users/:username
However I want to always want users to use the first URL as it looks more aesthetically pleasing. I could just redirect straight from the ID route, but with the planned friends and groups, I will end up with URLS such as:
https://domain.com/en/community/id/:userid/friends
https://domain.com/en/community/users/:username/friends
https://domain.com/en/community/id/:userid/groups
https://domain.com/en/community/users/:username/groups
How can I always redirect from /id/:userid to /users/:username but keep the rest of the URL?
The first task is matching all URLs with /id/:userid to use the same route callback.
The second task is to replace the /id/:userid with /users/:username.
Can these two tasks be achieved with Regular Expressions?
Thank you very much.

Okay, it turns out it was very simple to allow the user ID alias.
I can use an asterisk to capture all the other URLs, and then use a simple RegExp replace call to replace the ID with the Username.
app.get('/:lang/community/id/:id/*', function(req, res){
var id = req.params.id;
User.getByID(id, function(err, result, user){
var url = req.url.replace(new RegExp('/id/'+id, 'g'), '/users/'+user.name);
res.redirect(url);
}
});
This is the best solution I could think of. I hope it helps other people.

Related

express router not working with routes that include regex

I'm new to node and unable to create a simple route which will include regex as on of the parameter
// student.js - route file for route /student
app.get('/student/:/^[a-z0-9-]+$/', function(req,res){
res.send('student found');
});
when i hit localhost:3000/student/student-slug it says Cannot GET /student/student-slug
two more question
1) how to get param which is of regex, usually we can do this var _student = res.param.student_name but i'm unable to think for the regex
2) how to set optional param, let's say for pagination, route is like
/list/students/ will show list of last x student but /list/students/48 will offset that value to 48th row
this question may be duplicate but i'm unable to find answer
You need to encode the uri string before pass to request and decode it in your route handler.
Usage is very clear:
encodeURIComponent(str);
And for decoding use:
decodeURIComponent(str);
check the official documentation here
also do checkout this blog post on escape vs encode vs encodeURIComponent

Using regex to find a url pattern then redirect to a new one?

Sorry for the sloppy title, what i am trying to accomplish is an extension that will read my current url, and if it falls under a certain pattern then it will redirect me to a new page.
To further explain here is an example:
Every time i get a url like this: http://giant.gfycat.com/DownrightDismalElkhound.gif (giant.*.gif)
I want to be redirected to this: http://gfycat.com/DownrightDismalElkhound (giant.*.gif)
I have never written a chrome extension before so i was hoping someone could point me to a good resource to be able to learn how to do this.
var url = window.location.href;
if (!url.match(/giant\./) && !url.match(/\.gif$/)){
window.location.href = 'http://www.cnn.com';
}

Routing issue in codeigniter regex

Route are defined as
$route['hotels/([a-z]+)/(:any)'] = "hotels/city/$1/$2";
$route['hotels/placename/fivestar'] = "hotels/placename/star/fivestar";
I want to execute the city action in hotels controller when some one type url like
http://website.com/hotels/myspecificcity/fivestar
the above first route is not working. it always load 2nd route . can some one please guide me
i don't want to remove 2nd route though as i will using for other purposes
Thanks

Using cookies to filter data in Google Analytics

I am trying to filter Google Analytics data for my company site based on a cookie. I don't want to track internal traffic, but I can't just filter based on an IP address range because there are some internal users who we want to still track. I have some pretty simple code for adding a cookie, but I am just not sure where to add the code. I am really new to cookies, and couldn't find anything online that was clear on how to actually add or use the cookie.
<html>
<head>
<title>Remove My Internal Traffic from Google Analytics</title>
<script type="text/javascript">
var _gaq = _gaq || [];
_gaq.push(['_setAccount', 'UA-XXXXX-YY']);
_gaq.push(['_setVar','employee']);
_gaq.push(['_trackPageview']);
(function() {
var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
ga.src = ('https:' == document.location.protocol ? 'https://ssl' : http://www') + '.google-analytics.com/ga.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
})();
So my question is, where does this code actually go? Thanks for helping out my novice skills with cookies.
Do not use setVar (this is deprecated), use _setCustomVar:
_setCustomVar(index, name, value, opt_scope)
The call goes before the _trackPageview Call.
There are five custom vars in standard GA (50 in premium), that's "index". 'Name' and 'value' should be clear.
CustomVars are either valid for the current page, for the session or for the visitor (in the last case they are valid until the visitors clears the cookies in his browsers unless he waits six months before he visits you site again).
Like every instruction with the asynonchronous GA code this is "pushed" on the gaq-Array, so the correct call would be:
_gaq.push(['_setCustomVar',
1, // This custom var is set to slot #1. Required parameter.
'Items Removed', // The name acts as a kind of category for the user activity. Required parameter.
'Yes', // This value of the custom variable. Required parameter.
2 // Sets the scope to session-level. Optional parameter.
]);
which is taken from the Google documentation here:
https://developers.google.com/analytics/devguides/collection/gajs/gaTrackingCustomVariables#setup.
I still maintain that for your use case the opt-out plugin is the better solution.
UPDATE: Thinking about it I don't think you need setCustomVar or custom cookies at all. Have your employees go to your website via a link like:
mywebsite.com?utm_source=allyourbasearebelongtous
Then go to the profile settings and create a custom filter, set to exclude, filter field "campaign source" , filter pattern "allyourbasearebelongtous" (or whatever name you gave to your campaign parameter).
This uses also a cookie (the standard google cookie) but does not need any custom code at all. The campaign source parameter is valid until they visit another campaign geared towards your site, so if somebody wants to test the GA code they need to delete their cookies or use incognito mode (but that't not different from setting a custom cookie or setCustomVar-methods).

Codeigniter route regex - match any string except 'admin'

I'd like to send any route that doesn't match an admin route, to my "event" controller. This seems to be a fairly common requirement and a cursory search throws up all sorts of similar questions.
The solution, as I understand, seems to be using a negative lookahead in the regex. So my attempt looks like this:
$route['(?!admin).*'] = "event";
..which works. Well, sort of. It does send any non-admin request to my "event" controller, but I need it to pass the actual string that was matched: so /my-new-event/ is routed to /event/my-new-event/
I tried:
$route['(?!admin).*'] = "event/$0";
$route['(?!admin).*'] = "event/$1";
$route['(?!admin)(.*)'] = "event/$0";
$route['(?!admin)(.*)'] = "event/$1";
... and a few other increasingly random and desperate permutations. All result in a 404 page.
What's the correct syntax for passing the matched string to the controller?
Thanks :)
I don't think you can do "negative routing".
But as routes do have an order : "routes will run in the order they are defined. Higher routes will always take precedence over lower ones." I would do my admin one first then anything else.
If I suppose your admin path is looking like "/admin/..." I would suggest :
$route['admin/(:any)'] = "admincontroller/$1";
$route['(:any)'] = "event/$1";