Reputation: 2444
I allow users to upload images to my website. Some of these images have spaces in the name and stuff, and I want to avoid that altogether. Therefore, I want to hash the name of the image.
Is there a hash function that comes with javascript? I would rather not write my own, so should I consider writing/obtaining an md5 hash? Is there something built-in that I could use instead?
Upvotes: 0
Views: 1399
Reputation: 147523
If you simlpy want to make the string web-safe, use encodeURI or encodeURIComponent and then decode using decodeURI or decodeURIComponent as appropriate.
e.g.
var s = '*&@^# %@$!*)) jja;s kldfj';
var eS = encodeURIComponent(s); // *%26%40%5E%23%20%25%40%24!*))%20jja%3Bs%20kldf
alert(decodeURIComponent(eS)); // *&@^# %@$!*)) jja;s kldf
Every web server and client in use should have native support.
Upvotes: 1
Reputation: 17134
Well, if you must you can generate a slug:
function string_to_slug(str) {
str = str.replace(/^\s+|\s+$/g, ''); // trim
str = str.toLowerCase();
// remove accents, swap ñ for n, etc
var from = "àáäâèéëêìíïîòóöôùúüûñç·/_,:;";
var to = "aaaaeeeeiiiioooouuuunc------";
for (var i=0, l=from.length ; i<l ; i++) {
str = str.replace(new RegExp(from.charAt(i), 'g'), to.charAt(i));
}
str = str.replace(/[^a-z0-9 -]/g, '') // remove invalid chars
.replace(/\s+/g, '-') // collapse whitespace and replace by -
.replace(/-+/g, '-'); // collapse dashes
return str;
}
but, i think the other posters are right by saying you should do it on the server side. the only thing i think diffrently is to use a Guid as the image filename.
Upvotes: 0
Reputation: 6432
See this MD5 Implementation by Paj
Header:
/*
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
* Digest Algorithm, as defined in RFC 1321.
* Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
* Distributed under the BSD License
* See http://pajhome.org.uk/crypt/md5 for more info.
*/
Upvotes: 0
Reputation: 3558
Is there a reason that this needs to be done in JavaScript. It might be better to compute this on the server side once the file is uploaded and then give it back to the user once the operation is complete.
Upvotes: 0