[英]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在这种情况下,为了检查我是否有一个 substring 并且其中包含折扣,我已将数组转换为字符串
const arrayToString = tags.toString();
The output: output:
const tagsArrayToString = size-1,size-2,discount-wyx;
And I check if with a IF statement like this:我检查是否使用这样的 IF 语句:
if ( tagsArrayToString.indexOf("discount") !== -1 ) { doSomething }
So far so good.到目前为止,一切都很好。 But how can I get the full String like "discount-xyz" ?
但是我怎样才能得到像"discount-xyz"这样的完整字符串呢?
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.我不会将
tags
数组转换为字符串 - 您已经将字符串很好地分开了,这只会让事情变得更难。
Instead, you could filter
the array:相反,您可以
filter
数组:
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:或者,如果您知道只有一个这样的字符串,您可以使用
find
来获取它:
const relevantTag = tags.find(t => t.includes('discount'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.