Удалите любые пробелы при вводе в текстовое поле на веб-странице

Если Вы действительно хотите полностью удалить файлы из репозитория, необходимо сделать svndump в файл, отфильтровать версии и/или пути к файлам, Вы не хотите, делаете новый repo и svnload фильтрованный дамп в новый репозиторий. Вы захотите тщательно читать книжный раздел SVN по обслуживанию репозитория , прежде чем Вы сделаете любое из этого и удостоверитесь, что не удаляете существующий repo, пока Вы не уверены, что новый имеет материал, который Вы хотите.

5
задан Josh Stodola 18 March 2010 в 14:37
поделиться

5 ответов

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

Вы должны дополнительно обработать событие blur , потому что пользователь может использовать контекстное меню для вставки;)

25
ответ дан 18 December 2019 в 05:49
поделиться

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.

8
ответ дан 18 December 2019 в 05:49
поделиться

на лету? Возможно, при каждом нажатии клавиши возьмите строку в текстовом поле

$('#id').val($.trim($('#id').val());  

. Это удалит все лишние пробелы спереди и сзади.

0
ответ дан 18 December 2019 в 05:49
поделиться

Вы можете попробовать это так:

$("input").keypress(function (e) {
   $(this).val($(this).val().replace(' ',''));
}
-1
ответ дан 18 December 2019 в 05:49
поделиться

Я использую следующий код:

<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;
} 

строка регулярного выражения содержит то, что я хочу заменить ... у меня есть только числовые поля:

var pattern = new RegExp('[^0-9]+', 'g'); 
-3
ответ дан 18 December 2019 в 05:49
поделиться
Другие вопросы по тегам:

Похожие вопросы: