Javascript jQuery - given comma-separated list how to determine if exsits value

Define a list such as:

1,3,412,51213,djdd@asdasd.net, blahblah, 123123123123

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

<input type="text" value="1,3,412,51213,djdd@asdasd.net, blahblah, 123123123123, wow@wow.com" />

How to determine if a value exists, for example 3 or blahblah or wow@wow.com ?

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

thank

+3
source share
5 answers

Like this:

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

A call replaceremoves any spaces after commas.
inArrayreturns the match index.

+6
source

Using jQuery:

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

existsnow a boolean value indicating whether it was found searchTermin the values.

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

You may be too picky about matching values ​​using "===" if it should be of the same type. Otherwise, just use "==", as it will compare the int with the string as you probably expect.

+1
source

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

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

0
source

This will do the following:

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

And this ensures that leading and trailing spaces are also ignored (I assume you want to).

0
source

Source: https://habr.com/ru/post/1783293/


All Articles