Skip to content

Instantly share code, notes, and snippets.

@myersjustinc
Created November 8, 2011 16:52
Show Gist options
  • Save myersjustinc/1348342 to your computer and use it in GitHub Desktop.
Save myersjustinc/1348342 to your computer and use it in GitHub Desktop.
JS port of django-tagging's tagging.utils.parse_tag_input(), licensed MIT. See http://code.google.com/p/django-tagging/source/browse/trunk/tagging/utils.py for original Python.
// Output should pass all tests in tagging.tests.tests.TestParseTagInput except '"one two'
// and '"one two three'. Not sure why those fail, but I figured I should go ahead and
// post what I've got, anyway.
function parseTagInput(tagText) {
function eliminateDuplicates(arr) {
// From Rhett Anderson (@nosredna):
// http://dreaminginjavascript.wordpress.com/2008/08/22/eliminating-duplicates/
// Modified to fit my coding style, but that should be about it.
var out = [];
var obj = {};
for (var i = 0, j = arr.length; i < j; i++) {obj[arr[i]]=0;}
for (var i in obj) {out.push(i);}
return out;
}
if (typeof(tagText) == 'undefined' || tagText == null || tagText.length == 0) {return [];}
if (tagText.indexOf(',') == -1 && tagText.indexOf('"') == -1) {
return eliminateDuplicates(tagText.split(' ')).sort();
}
var tags = [];
var buffer = [];
var toBeSplit = [];
var sawLooseComma = false;
var openQuote = false;
for (var i = 0, j = tagText.length; i < j; i++) {
var c = tagText[i];
if (c == '"') {
if (buffer.length) {
toBeSplit.push(buffer.join(''));
buffer = [];
}
openQuote = true;
c = tagText[++i];
while (c != '"' && c != undefined) {
buffer.push(c);
c = tagText[++i];
}
if (buffer.length) {
var tag = buffer.join('').trim();
if (tag.length) {tags.push(tag);}
buffer = [];
}
if (c != undefined) {openQuote = false;}
} else {
if (!sawLooseComma && c == ',') {sawLooseComma = true;}
buffer.push(c);
}
}
if (buffer.length) {
if (openQuote && buffer.indexOf(',') != -1) {sawLooseComma = true;}
toBeSplit.push(buffer.join(''));
}
if (toBeSplit.length) {
var delimiter = ' ';
if (sawLooseComma) {delimiter = ',';}
for (var k in toBeSplit) {
var chunk = toBeSplit[k];
var rawTags = chunk.split(delimiter);
for (var l in rawTags) {
rawTags[l] = rawTags[l].trim();
if (rawTags[l]) {tags.push(rawTags[l]);}
}
}
}
return eliminateDuplicates(tags).sort();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment