jQuery hashtag input control

This jQuery snippet will turn an INPUT element into a hashtag input control. For example, if the user type "jobs business networking", it will translate it into "#jobs #business #networking" as they are typing it. It will also string commas and whitespace.

$(document).ready(function() {

 $("input.hastags").bind("keyup", function () {

  /* replaces text as you type with hashtags */

  var input = $(this);
  var value = input.val();
  var ends_with_space = (value.substr(-1) == " ");

  var hashed_value = "";
  var parts = value.split(" ");
  for (var i = 0; i < parts.length; i++) {
   var part = parts[i];
   if (part.indexOf("#") != 0) {
    part = "#" + part;
   }
   if (part != "#") {
    if (hashed_value == "") {
     hashed_value = part;
    } else {
     hashed_value += " " + part;
    }
   }
  }
  if (ends_with_space) {
   hashed_value = hashed_value + " ";
  }
  input.val(hashed_value.replace(",", ""));
 });

});


I'm currently working at NerdWallet, a startup in San Francisco trying to bring clarity to all of life's financial decisions. We're hiring like crazy. Hit me up on Twitter, I would love to talk.

Follow @chase_seibert on Twitter