How could I, on the fly, remove spaces entered into a textbox while the person is typing?
问题:
回答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 ;)
回答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.
回答3:
on the fly? Perhaps on every keypress event, take the string in the textbox
$('#id').val($.trim($('#id').val());
This will remove any extraneous spaces in front and back.
回答4:
You could try it like this:
$("input").keypress(function (e) {
$(this).val($(this).val().replace(' ',''));
}
回答5:
I use following code:
<input type="text" onkeyup="fixme(this)" onblur="fixme(this)"/>
function fixme(element) {
var val = element.value;
var pattern = new RegExp('[ ]+', 'g');
val = val.replace(pattern, '');
element.value = val;
}
the regexp line contains what i want replaced... i have for number only fields:
var pattern = new RegExp('[^0-9]+', 'g');