JSFiddle - React, Tailwind, and code Playground

Fess Up Tags Input cleanTags Function

by Jennifer Perrin

HTML

<input id="testone" type="text" style="width:90%" />

JavaScript

$(document).ready(function() {
    $("#testone").change(function() {
        cleanTags($(this).attr('id'));
    });
    
    $('#testone').keyup(function(e) {
        var tagsInput = $(this).val();
        var tagsString = tagsInput.replace(/[ ,]+/g, ",");

        $(this).val(tagsString);
    });
    
    $('#testone').keypress(function(e) {
        var regex = new RegExp("^[ a-zA-Z]+$");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (regex.test(str)) {
            return true;
        }

        e.preventDefault();
        return false;
    });

});

/**
 * Format the Tags Field text values
 * Remove Duplicates
 * Remove leading and trailing blanks, extra commas, etc.
 */

function cleanTags(idToClean) {
    var stringToClean = jQuery.trim($('#'+idToClean).val());

    // If there is no text entered then don't continue
    if (stringToClean.length < 1) {
        return (false);
    }

    // Replace characters that we dont want
    stringToClean = stringToClean.replace(/[,]{2,}/g, ',').replace(/%/g, '').replace(/_/g, '').replace(/\r\n|\n|\r/g, ",");

    // Split string to an array at every comma 
    var tempArr = stringToClean.split(',');
    var uniqueArray = new Array();

    // Search for duplicates, if found delete em
    for (var i = 0; i < tempArr.length; i++) {
        tempArr[i] = jQuery.trim(tempArr[i]);

        if (tempArr[i] == '') {
            tempArr.splice(i, 1);
            i--;
        }

        if (uniqueArray[tempArr[i]] != undefined) {
            tempArr.splice(i, 1);
            i--;
        }
        uniqueArray[tempArr[i]] = '';
    }
    $('#'+idToClean).val(tempArr.join(','))
}