javascript jQuery - 给定一个逗号分隔的列表,如何确定一个值是否存在

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4588427/
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-25 14:13:49  来源:igfitidea点击:

javascript jQuery - Given a comma delimited list, how to determine if a value exists

javascriptjquery

提问by TheExit

given a list like:

给出一个列表,如:

1,3,412,51213,[email protected], blahblah, 123123123123

which lives inside of a input type"text" as a value:

它作为值存在于输入类型“文本”中:

<input type="text" value="1,3,412,51213,[email protected], blahblah, 123123123123, [email protected]" />

How can I determine if a value exists, like 3, or blahblah or [email protected]?

如何确定值是否存在,例如 3、blahblah 或 [email protected]

I tried spliting with inputval.split(',') but that only gives me arrays. Is search possible?

我尝试用 inputval.split(',') 进行拆分,但这只给了我数组。可以搜索吗?

回答by SLaks

Like this:

像这样:

if (jQuery.inArray(value, str.replace(/,\s+/g, ',').split(',')) >= 0) {
    //Found it!
}

The replacecall removes any spaces after commas.
inArrayreturns the index of the match.

replace调用会删除逗号后的所有空格。
inArray返回匹配的索引。

回答by Tatu Ulmanen

Utilizing jQuery:

使用 jQuery:

var exists = $.inArray(searchTerm, $('input').val().split(',')) != -1;

existsis now an boolean value indicating whether searchTermwas found in the values.

exists现在是一个布尔值,指示是否searchTerm在值中找到。

回答by John Fisher

var list = inputval.split(',');
var found = false;
for (var i=0; i<list.length; ++i) {
  if (list[i] == whateverValue) {
    found = true;
    break;
  }
}

You can be extra picky about the value matching by using "===" if it must be of the same type. Otherwise, just use "==" since it will compare an int to a string in a way that you probably expect.

如果必须是相同类型,您可以通过使用“===”对值匹配更加挑剔。否则,只需使用“==”,因为它会以您可能期望的方式将 int 与字符串进行比较。

回答by Dutchie432

You'l want to use var arr = theString.split(',')and then use var pos = arr.indexOf('3');

你会想使用var arr = theString.split(',')然后使用var pos = arr.indexOf('3');

http://www.tutorialspoint.com/javascript/array_indexof.htm

http://www.tutorialspoint.com/javascript/array_indexof.htm

回答by Nathan MacInnes

This'll do it:

这样做:

var val = $('myinput').val()
val = ',' + val.replace(', ',',').replace(' ,',',').trim() + ','; // remove extra spaces and add commas
if (val.indexOf(',' + mySearchVal + ',' > -1) {
    // do something here
}

And it makes sure start and end spaces are ignored too (I assume that's what you want).

并且它确保开始和结束空格也被忽略(我认为这就是你想要的)。