Skip to content

Instantly share code, notes, and snippets.

@thisislawatts
Forked from onyxfish/README.md
Last active August 29, 2015 14:15
Show Gist options
  • Save thisislawatts/668d6010f6fdf1367451 to your computer and use it in GitHub Desktop.
Save thisislawatts/668d6010f6fdf1367451 to your computer and use it in GitHub Desktop.

This script for Google Spreadsheets allows you to generate slugs for your data such as might be used for creating unique urls.

Use it like this!

# A B C
1 a b slug
2 foo baz bing =slugify(A2:B4)
3 bar BAZ
4 FOO baz-bing

And you get this!

# A B C
1 a b slug
2 foo baz bing foo-baz-bing
3 bar BAZ bar-baz
4 FOO baz-bing foo-baz-bing-2
function escapify(value) {
value = value.toLowerCase();
value = value.replace(/[^\w\s-]/g, '');
value = value.replace(/\s+/g, '-')
return value.replace(/\-+/,'-');
}
function slugify(values) {
/*
* Convert the the vs in a range of cells into slugs.
*/
slugs = [];
if ( typeof values === 'object' ) {
for (var row = 0; row < values.length; row++) {
var bits = [];
for (var column = 0; column < values[row].length; column++) {
var value = values[row][column];
bits.push( escapify( value ) );
}
var base = bits.join('-');
var i = 1;
var slug = base;
while (slugs.indexOf(slug) >= 0) {
i++;
slug = base + '-' + i;
}
slugs.push(slug);
}
output = [];
for (var s = 0; s < slugs.length; s++) {
output.push([slugs[s]]);
}
return output;
}
return escapify( values );
}
function test() {
/*
* Test the slugify function.
*/
var TESTS = [
'foo',
];
var RESULTS = [
'foo',
'foo-baz-bing',
'bar-baz',
'foo-baz-bing-2'
];
var output = slugify(RESULTS);
for (var t = 0; t < TESTS.length; t++) {
var test = TESTS[t];
var result = RESULTS[t];
Logger.log("[" + test + "] == " + result);
Logger.log((output[t][0] == result) + " ... " + output[t][0]);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment