1

I have a search input box on a site. If the user enters text in the input box I like to replace all [space]-characters with ' & ' (in words: space&space)

But I have a small mistake in my code because if the user tries to delete text (backspace) then it inserts a ' & ' again if the last char was a replaced space...

See my example on JSFiddler: http://jsfiddle.net/JFEb4/

Any ideas?

Code:

$("[name='search']").keyup(function() {

    var input = $(this).val().replace(/ & /g, "x");

    if (input.indexOf(" ") >= 0) {
        $(this).val(input.replace(' ', ' & ').replace(/x/g, " & "

});
4

2 回答 2

3

A better way would be to check if the spacebar was pressed before the characters are added to the value, and if it was, prevent the character from outputting and add & instead.
That would also avoid the backspace issue all together :

$("[name='search']").on('keydown', function(e) {
    if (e.which === 32) {
        e.preventDefault();
        this.value = this.value + ' & ';
    } 
});

FIDDLE

于 2013-07-25T15:28:34.227 回答
0

Here is my take:

$("[name='search']")
    .on('keyup paste', function(e) {

        var replaceSpaces = function(el) {
            return function() {
                $(el).val($(el).val().replace(/(^|[^&])\s+($|[^&])/g, '$1 & $2'));
            };
        } (this);

        if (e.type === 'keyup' && e.which === 32) {
            replaceSpaces();
        } else if (e.type === 'paste') {
            setTimeout(replaceSpaces, 5);                
        }

    });

(this code on jsFiddle)

于 2013-07-25T17:40:00.910 回答