JavaScript 如果字符串是逗号分隔的字符串

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

JavaScript if string is in comma delimited string

javascriptjquery

提问by impress

I have string like this: str = "ball, apple, mouse, kindle";

我有这样的字符串: str = "ball, apple, mouse, kindle";

and I have another text to search in this string: search = 'apple';

我还有另一个文本要在这个字符串中搜索: search = 'apple';

How to determine using JavaScript if appleexist in comma delimited string?

如果apple以逗号分隔的字符串中存在,如何确定使用 JavaScript ?

P.S: strcan be with or without spaces between comma and next item.

PS:str逗号和下一项之间可以有或没有空格。

回答by machineghost

Simple solution:

简单的解决方案:

var str = "ball, apple, mouse, kindle";
var hasApple = str.indexOf('apple') != -1;

However, that will also match if strcontains "apple fritters":

但是,如果str包含“apple fritters” ,这也将匹配:

var str = "ball, apple fritters, mouse, kindle";
var hasApple = str.indexOf('apple') != -1; // true

There are different approaches you could do to get more specific. One would be to split the string on commas and then iterate through all of the parts:

您可以采取不同的方法来获得更具体的信息。一种是用逗号分割字符串,然后遍历所有部分:

var splitString = str.split(',');
var appleFound;
for (var i = 0; i < splitString.length; i++) {
    var stringPart = splitString[i];
    if (stringPart != 'apple') continue;

    appleFound = true;
    break;
}

NOTE: You could simplify that code by using the built-in "some" method, but that's only available in newer browsers. You could also use the Underscore library which provides its own "some" method that will work in any browser.

注意:您可以使用内置的“some”方法来简化该代码,但这仅适用于较新的浏览器。您还可以使用 Underscore 库,它提供了自己的“一些”方法,可以在任何浏览器中使用。

Alternatively you could use a regular expression to match "apple" specifically:

或者,您可以使用正则表达式专门匹配“apple”:

var appleFound = /\Wapple,/.test(',' + str + ',');

However, I think your real best bet is to not try and solve this yourself. Whenever you have a problem like this that is very common your best bet is to leverage an existing library. One example would be the Underscore String library, especially if you're already using Underscore. If not, there are other general purpose string utility (eg. String.js) libraries out there you can use instead.

但是,我认为您真正最好的选择是不要尝试自己解决这个问题。每当您遇到此类非常常见的问题时,最好的办法就是利用现有的库。一个例子是 Underscore String 库,特别是如果您已经在使用 Underscore。如果没有,您可以使用其他通用字符串实用程序(例如 String.js)库。

回答by Felix Kling

To really test whether the exact character sequence "apple" is an item in your comma separated list (and not just a substring of the whole string), you can do (considering optional spaces before and after the value):

要真正测试确切的字符序列“apple”是否是逗号分隔列表中的一个项目(而不仅仅是整个字符串的子字符串),您可以这样做(考虑值前后的可选空格):

If Array#indexOfis available:

如果Array#indexOf可用:

var items = str.split(/\s*,\s*/);
var isContained = items.indexOf('apple') > -1;

If Array#someis available:

如果Array#some可用:

var items = str.split(/\s*,\s*/);
var isContained = items.some(function(v) { return v === 'apple'; });

With a regular expression:

使用正则表达式

var isContained = /(^|,)\s*apple\s*($|,)/.test(str);

回答by Idan Magled

you can turn the string in to an array and check the search string is in it.

您可以将字符串转换为数组并检查搜索字符串是否在其中。

var stuffArray = str.split(","); 
var SearchIndex = stuffArray.indexOf("Apple");

the search SearchIndex represent the position in the array. if the SearchIndex < 0 the item is not found.

搜索 SearchIndex 表示数组中的位置。如果 SearchIndex < 0,则未找到该项目。

回答by Jamiec

You can do this the very easy, yet error prone way of checking the index of the string applein your comma separated list:

您可以使用非常简单但容易出错的方法来检查apple逗号分隔列表中字符串的索引:

var str = "ball, apple, mouse, kindle"
var index = str.indexOf('apple')
alert(index) 

Checking the result is >-1tells you that the strcontains the string apple. However, this will give you false positives where for example stris:

检查结果>-1告诉您str包含字符串apple。但是,这会给您误报,例如str

var str = "ball, crab apple, mouse, kindle"

That will still give you an index for applethat is >-1- probably not what you want.

这仍将给你一个指标apple就是>-1-你想可能不是什么。

回答by undefined

You can use String.split()and Array.indexOf().

您可以使用String.split()Array.indexOf()

var str = "ball, apple, mouse, kindle";
var search = "apple";
var arr = str.split(", ");
if (arr.indexOf(search) !== -1) {
   alert('yes');
} else {
   alert('no');
}

回答by doniyor

please note, for this code, you need jquery library

请注意,对于此代码,您需要 jquery 库

str = "ball, apple, mouse, kindle";
str_arr = str.split(',');
for (i = 0; i < str_arr.length; i++) { 
   if($.trim(str_arr[i]) === "apple"){
     alert('yiha i found an apple here. here it is: ' + str_arr[i]);
   }
}

回答by John L

There are some great answers here arleady, but I thought I'd give an alternative using regex's. This will be case insensitive, so will match 'Apple' or 'apple'. Also, it will not match "Appleby's" or "apple pie", so you'll be spared false positives (or the regex can be changed to include those):

这里有一些很好的答案,但我想我会使用正则表达式给出一个替代方案。这将不区分大小写,因此将匹配“Apple”或“apple”。此外,它不会匹配“Appleby's”或“apple pie”,因此您将避免误报(或者可以更改正则表达式以包括这些):

var str = "ball, apple, mouse, kindle";
var whatToFind = "apple";
var myRegEx = new RegExp(",\s*" + whatToFind + "\s*,", "i");
myRegEx.test(str);

That was the basic regex. Here it is inside a function and with some tests:

那是基本的正则表达式。这是在一个函数内并进行了一些测试:

var str = "ball, apple, mouse, kindle";
var str2 = "ball, apple pie, house,cat";
var str3 = "ball,Apple,house, cat";
var str4 = "ball,Appleby's, peach, dog";
strs = [str, str2, str3, str4];
var searchFor = "apple";


var matches = function (stringToSearch, whatToFind)
{
    var myRegEx = new RegExp(",\s*" + whatToFind + "\s*,", "i");
    return myRegEx.test(stringToSearch);
}

strs.forEach(function (st) {
    var confirm = " was ";
    if(matches(st, searchFor)==true)
        confirm = " was ";
    else
        confirm = " was not ";
    console.log( '"' + searchFor + '"' + confirm + "found in " + '"' + st + '"');
});

Here is the output:

这是输出:

"apple" was found in "ball, apple, mouse, kindle"

"apple" was not found in "ball, apple pie, house,cat"

"apple" was found in "ball,Apple,house, cat"

"apple" was not found in "ball,Appleby's, peach, dog"

在“ball, apple, mouse, kindle”中发现了“apple”

在“ball, apple pie, house,cat”中没有找到“apple”

在“ball,Apple,house, cat”中发现了“apple”

在“ball,Appleby's, peach, dog”中没有找到“apple”

回答by Brian

Here's another solution using regular expressions

这是使用正则表达式的另一种解决方案

//some test csv
var t = '1,2,3,4,32,apple,apple struddle,applestruddle,41,42,43';

now create a regular expression 'reg' here .. it can be done hardcoded like

现在在这里创建一个正则表达式“reg”..它可以像硬编码一样完成

var reg =  /(^|,\s{0,1})\bapple struddle\b(,|$)/;

or programmatically like

或以编程方式喜欢

var check_value = "apple";
var reg = new RegExp("(^|,\s{0,1})\b" + check_value + "\b(,|$)","g");

and you can simply call

你可以简单地打电话

if(reg.test(t)){
  console.log("apple .. no struddle!!");
}

Just a note on the reg exp .. I put in a \s{0,1} after the comma just to cater for a ", " vs a "," seperator.. obviously .. sort out your spacing requirements to suite yourself ;)

只是关于 reg exp 的一个注释 .. 我在逗号后面放了一个 \s{0,1} 只是为了迎合“,”与“,”分隔符......显然......整理出你的间距要求以适应自己;)