Remove any spaces while typing into a textbox on a web page

13,956

Solution 1

$(function() {
  var txt = $("#myTextbox");
  var func = function() {
    txt.val(txt.val().replace(/\s/g, ''));
  }
  txt.keyup(func).blur(func);
});

You have to additionally handle the blur event because user could use context menu to paste ;)

Solution 2

This ridiculousness about regular expressions being slow/bad for this task needs to be put the the test. This may not be the most accurate benchmark, but it will do to illustrate my point.

// Modified roosteronacid's example to consider all whitespace characters
function sanitizer(s) {
    var a = s.split(""),
        i = a.length,
        r = "";

    while (i) {
        i--;
        if (a[i] !== " " || a[i] !== "\t" || a[i] !== "\r" || a[i] !== "\n" || a[i] !== "\f" || a[i] !== "\v") {
            r += a[i];
        }
    }

    return r;
}

// Regular expression method wrapped in a function to incur the same overhead
function regexp(s) {
  return s.replace(/\s+/g, '');
}

var iterations = 10000;
// 1024 characters or good meausure
var text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Mauris luctus tristique ante, ac suscipit tortor consequat at. Fusce id tortor quis felis faucibus dignissim. Pellentesque viverra pellentesque eros, ac sagittis quam cursus a. Nullam commodo mauris eget nisi luctus vitae ultricies leo volutpat. Morbi quis quam id elit accumsan semper. Praesent aliquam aliquam tortor vel vulputate. Nulla adipiscing ipsum vitae est luctus imperdiet. Suspendisse potenti. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus at urna ut leo ornare commodo. Quisque eros dolor, adipiscing quis malesuada quis, molestie nec lectus. Quisque et odio nibh. Integer mattis tincidunt ligula, eu scelerisque erat posuere non. Sed ipsum quam, fringilla id porttitor ac, placerat quis nunc. Praesent sodales euismod ultricies. In porta magna metus. Morbi risus risus, hendrerit sit amet ultrices eu, interdum placerat massa. Nunc at leo dui. Morbi eu nunc mi, at ullamcorper felis. Duis et metus metus. ";

var s = new Date();
for ( var i=0; i<iterations; ++i ) {
  sanitizer(text);
}

console.log((new Date()).getTime() - s.getTime());

var s = new Date();
for ( var i=0; i<iterations; ++i ) {
  regexp(text);
}

console.log((new Date()).getTime() - s.getTime());

Results of 8 executions:

# Initial times
sanitizer: 5137, 8927, 8817, 5136, 8927, 5132, 8807, 8804
regexp:    1275, 1271, 1480, 1278, 1274, 1308, 1270, 1270

# Dropped highest and lowest values
sanitizer: 5137, 8817, 5136, 8927, 8807, 8804
regexp:    1275, 1271, 1278, 1274, 1308, 1270

# Averages
sanitizer: (5137 + 8817 + 5136 + 8927 + 8807 + 8804) / 6 = 7604.66667
regexp:    (1275 + 1271 + 1278 + 1274 + 1308 + 1270) / 6 = 1279.33333

Turns out using regular expressions is 594% faster.

See Josh Stodola answer for the implementation.

Edit: I notice that roosteronacid's method has changed; however, using r as an array makes it even slower.

Share:
13,956
mrblah
Author by

mrblah

test testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest testtest test asdf asdf

Updated on June 19, 2022

Comments

  • mrblah
    mrblah almost 2 years

    How could I, on the fly, remove spaces entered into a textbox while the person is typing?

  • cllpse
    cllpse over 14 years
    Regular expressions are slow. Handling the blur-event is not needed if you bind your logic to the keyup-event.
  • cllpse
    cllpse over 14 years
    No need to waste performance, wrapping "this" in a jQuery object. We are after all talking about inputs. Both a textarea and an input has got the .value property.
  • cllpse
    cllpse over 14 years
    Belay that. The blur event is a smart move :)
  • Justin Johnson
    Justin Johnson over 14 years
    @roosteronacid the speed of regular expressions in this case is inconsequential.
  • cllpse
    cllpse over 14 years
    I'm all for the whole "do not pre-optimize". But if it can be done faster, why not do so? :) -- (faster == cleaner, in my head anyways).
  • Josh Stodola
    Josh Stodola over 14 years
    Faster? You can't be serious. If you really think your backwards loop is going to blow my mini RegEx out of the water in performance, than I would consider your username to be precise.
  • mrblah
    mrblah over 14 years
    do I add this to my $(document).ready(); function or outside of that?
  • cllpse
    cllpse over 14 years
    I didn't say your code will blow up--it's neat and tidy, and I like it. I guess it's just a matter of opinion. When it comes to JavaScript, I like to create code that runs as fast as possible. Considering that this is a knowledgebase for novice -as well as experienced programmers, why not try to dish out some best-practices while your at it?
  • cllpse
    cllpse over 14 years
    @homestead: $(document).ready(function () { ... }) creates a closure. If you add Josh's code inside of that, you can only access it inside that closure. This way you avoid polluting the global namespace as well. If you are only gonna use this functionality in one interface, I'd suggest you put it inside $(document).ready( ... );
  • Justin Johnson
    Justin Johnson over 14 years
    @roosteronacid It's not a matter of opinion, the regexp is faster than your code. See my answer.
  • M.Sworna Vidhya
    M.Sworna Vidhya over 14 years
    well put. Was going to do the same thing. (I added a link to your answer. Hope you don't mind.)
  • mrblah
    mrblah over 14 years
    ok it worked. Have you guys seen twitter's implementation? A space can never be entered at all! see the username field: twitter.com/signup
  • Josh Stodola
    Josh Stodola over 14 years
    +1 for doing the benchmarks. I was going to do this, but did not have the time. Whats-his-name needed to see this answer!