How to match a comma separated value with Angular.js / Javascript

I need help. I need to map some value to a single variable containing a value that is separated by commas using Angular.js or Javascript. I explain my code below.

var special="2,1,4,5";

Here I need to search for let say say 1whether or not this line is separated by a comma. If this value is present, it will return true otherwise false. Please help.

+4
source share
4 answers

With split array

var found = special.split(",").indexOf("1") > -1;

var special="2,1,4,5";
var found = special.split(",").indexOf("1") > -1;
console.log(found); // true
Run codeHide result

Just to prove that String indexOf will not work

var special="2,11,4,5";
var found = special.indexOf("1") > -1;
console.log(found); // true but actual should be false as there is no 1
Run codeHide result
+4
source

:

var specialArray = special.split(',');

, indexOf .

var itemIndex = specialArray.indexOf('1');

itemIndex -1, , , . indexOf , -1, .

0

Try it,

var special="2,1,4,5";
var searchFor="1";
var index=special.split(",").indexOf(searchFor);
if(index === -1) return false;
else return true;
0
source

To do this, you can use the regular expression:

/(^|,)1(,|$)/.test("2,1,4,5") // => true

just check the negative case

/(^|,)1(,|$)/.test("2,11,4,5") // => false

If you have a multi-line string (containing \r\n), use /(^|,)1(,|$)/minstead

0
source

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


All Articles