javascript 用jQuery查看输入是否有空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/13257007/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 18:13:33  来源:igfitidea点击:

See if Input Has Spaces with jQuery

javascriptjquery

提问by streetlight

I'm trying to write a function that reads a inputs value, and determines if a space has been used in it's creation. I'm not trying to trim anything -- just see if it would have needed the ability to trim.

我正在尝试编写一个函数来读取输入值,并确定在创建过程中是否使用了空格。我不想修剪任何东西——只是看看它是否需要修剪的能力。

I'm not even sure where to begin on this, so I don't have any code to look at. Please help if you can!

我什至不确定从哪里开始,所以我没有任何代码可以查看。如果可以的话请帮忙!

I was trying this solution but it doesn't seem to work (I don't think I'm using .has() correctly)

我正在尝试这个解决方案,但它似乎不起作用(我认为我没有正确使用 .has())

if ($('#id').val().has(" ")) {
            alert('has spaces')
        }

回答by Denys Séguret

Use valand indexOf:

使用valindexOf

var hasSpace = $('#myInputId').val().indexOf(' ')>=0;

If you want to test other types of "spaces" (for example a tabulation), you might use a regex :

如果要测试其他类型的“空格”(例如制表),可以使用正则表达式:

var hasSpace = /\s/g.test($('#myInputId').val());

Demonstration

示范

回答by May

Use contains for include space:

使用 contains 来包含空间:

var value = $('#myInputId').val();
if(value.contains(' ')){
   console.log("has space");
}

Or you can find with these ascII code &nbsp and \xA0

或者你可以用这些 ascII 代码   和 \xA0 找到

if(value.contains(' ')){
   console.log("has space");
}