简体   繁体   中英

How to allow only one space in JavaScript real time filtering

I' am use this custom function below to strip out unwanted characters from the textfield, this is done real time. The problem is that it allows spaces and users can enter as many spaces as they want, but I want allow only one space.

Is it possible?

function mask8(x){
        var string = document.getElementById(x)
        var regex = /[^A-Za-z ]/gi;
        $("#"+x).removeClass("error");
        if(string.value.search(regex) > -1) {
            string.value = string.value.replace(regex, "");
            $("#"+x).addClass("error");
        }
    }

If you just want to automatically collapse multiple spaces down to a single space without making it an error condition, you can do this:

function mask8(x){
    var obj = document.getElementById(x);
    var val = obj.value;
    var illegalChars = /[^A-Za-z ]/gi;
    $("#"+x).removeClass("error");
    // automatically collapse multiple spaces down to a single space, 
    // don't make it an error condition
    val = val.replace(/\s+/g, " ");
    if(val.search(illegalChars) > -1) {
        val = val.replace(illegalChars, "");
        $("#"+x).addClass("error");
    }
    obj.value = val;
}

If you want to make multiple spaces an error condition, then you could do this:

function mask8(x){
    var obj = document.getElementById(x);
    var val = obj.value;
    var illegalChars = /[^A-Za-z ]/gi;
    var illegalCharsOrMultipleSpaces = /[^A-Za-z ]|\s\s/gi;
    $("#"+x).removeClass("error");
    if(val.search(illegalCharsOrMultipleSpaces) > -1) {
        obj.value = val.replace(illegalChars, "").replace(/\s+/g, " ");
        $("#"+x).addClass("error");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM