简体   繁体   English

如何在 Javascript 中获取包含 substring 的完整字符串?

[英]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'));

Find the index of the discount tag using findIndex method, in turn find the tag itself via the index of the array.使用findIndex方法找到折扣标签的索引,然后通过数组的索引找到标签本身。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查字符串是否包含子字符串并在javascript中为其着色? - how to check if a string contains substring and color it in javascript? 如何在JavaScript中检查字符串是否包含子字符串 - How to check string contains substring in javascript 如何检查一个字符串在JavaScript中是否包含一个substring? - How to check whether a string contains a substring in JavaScript? 如何检查对象是否包含至少一个其值包含JavaScript子字符串的键? - How can I check if an object contains at least one key whose value contains a substring in JavaScript? 检查字符串是否包含JavaScript中的子字符串 - Check string contains substring in javascript 如何搜索 substring 并显示完整? - How can I search for substring and displayed the full? 如何使用Javascript将子字符串从字符串切到结尾? - How can I cut a substring from a string to the end using Javascript? 如何检查字符串是否包含JavaScript中的字符串数组中的子字符串 - how to check if a string contains a substring from an array of strings in JavaScript 如何在 JavaScript(打字稿)中检查字符串是否包含 substring? - How to check whether a string contains a substring in JavaScript(typescript)? 如何在窗口环境中获取我的 JavaScript UMD 包的完整字符串? `.toString()` 不工作 - How can I get full string of my JavaScript UMD package in window environment? `.toString()` is not working
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM