Henrique Medina
Henrique Medina

Reputation: 69

How can I get a full string that contains a substring in Javascript?

For example:

I have a array

const tags = ['size-1', 'size-2', 'discount-xyz']

In this case to check if I have a substring with discount in it, I have converted the array to a string

const arrayToString = tags.toString();

The output:

const tagsArrayToString = size-1,size-2,discount-wyx;

And I check if with a IF statement like this:

if ( tagsArrayToString.indexOf("discount") !== -1 ) { doSomething }

So far so good. But how can I get the full String like "discount-xyz"?

Upvotes: 1

Views: 545

Answers (2)

Vinay Sharma
Vinay Sharma

Reputation: 3797

Find the index of the discount tag using findIndex method, in turn find the tag itself via the index of the array.

const index = tags.findIndex(t => t.indexOf('discount') !== -1);
const discountTag = tags[index];

Upvotes: 1

Mureinik
Mureinik

Reputation: 312136

I wouldn't convert the tags array to a string - you already have the strings nice and separated, and this would only make things harder.

Instead, you could filter the array:

const filteredTags = tags.filter(t => t.includes('discount'));

Or, if you know there's just one such string, you could use find to get it:

const relevantTag = tags.find(t => t.includes('discount'));

Upvotes: 2

Related Questions