4

I need some help. I need to match some value with one variable containing value which is comma separated string using Angular.js or Javascript. I am explaining my code below.

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

Here I need to search lets say 1 is present in this comma separated string or not. If the given value is present it will return true otherwise false.Please help.

0

4 Answers 4

3

With array split

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

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


Just to prove that String's indexOf won't 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

Sign up to request clarification or add additional context in comments.

2 Comments

why to split when you can directly use indexOf on string
@AmberNemani Big NOOO. If you search for 1 and the element is 11, String's indexOf returns true. Added a demo for the same
1

Try this,

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

Comments

0

You can first convert the string to an array like this:

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

Once you have an array you can use indexOf to find the item in the array.

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

itemIndex will be -1 when the value you're looking for isn't in the array. When the result of indexOf is greater than -1 it is the index of the item in the array.

Comments

0

You can use regular expression for this:

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

just to test negative case

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

If you have multiline string (that contains \r\n), use /(^|,)1(,|$)/m instead

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.