如何检查输入是否只包含空格字符?即只有一个或多个空格,而没有其他字符

How can I check if an input contains space characters only. I.e. one or more spaces only and no other characters

本文关键字:空格 字符 有一个 其他 输入 检查 是否 何检查 包含      更新时间:2023-09-26

如果输入字段只包含空格,我需要检测focusout。只有1个或更多的空格,而不是任何其他字符?

目前它只检测它是否只包含1个空格

$("#myInput").on("focusout",function(){
    if($(this).val() ==" "){ 
        //do work
    }
});

使用正则表达式:

if (/^'s+$/.test($(this).val())) { ...

我会选择trim选项。

修剪输入值,然后检查是否为空。

if (!String.prototype.trim) {
    String.prototype.trim=function(){return this.replace(/^'s+|'s+$/g, '');};
    String.prototype.ltrim=function(){return this.replace(/^'s+/,'');};
    String.prototype.rtrim=function(){return this.replace(/'s+$/,'');};
    String.prototype.fulltrim=function(){return this.replace(/(?:(?:^|'n)'s+|'s+(?:$|'n))/g,'').replace(/'s+/g,' ');};
}

修剪和比较长度,并检查长度是否为零。

$("#myInput").on("focusout",function(){
    if($(this).val().length && $.trim($(this).val()).length === 0){ 
        alert("string contains one or more spaces")
    }
});
if (yourstring.match(/^'S+(['s'xA0]| )+/, '')){