在JavaScript中如何检查特定单词是否存在。

huangapple go评论64阅读模式
英文:

How do I check if specific words contain in JS

问题

I have a problem checking if the word "product" is there.
添加一个名为 "newProduct" 的标头,其值为 "yes"。
Right now my problem is that if the collectionName has a word of "e23product32", it doesn't add the header.

const productTags = [
  "product"
];

const collectionName = 'e23product32';

const headers = {
  ...(productTags.some((tag) => tag.includes(collectionName)) && {
    "newProduct": "yes",
  }),
};

console.log(headers);
英文:

I have a problem checking if the the word "product" is there.
add a header called "newProduct" with a value of "yes".
Right now my problem is that if the collectionName has a word of "e23product32", it doesn't add the header

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const productTags = [
  &quot;product&quot;
];

const collectionName = &#39;e23product32&#39;;

const headers = {
  ...(productTags.some((tag) =&gt; tag.includes(collectionName)) &amp;&amp; {
    &quot;newProduct&quot;: &quot;yes&quot;,
  }),
};

console.log(headers);

<!-- end snippet -->

答案1

得分: 1

你把支票拿反了... &quot;product&quot; 不包含(包括) &quot;e23product32&quot;,但 &quot;e23product32&quot; 包含 &quot;product&quot;

const productTags = [&quot;product&quot;];

const collectionName = &quot;e23product32&quot;;

const headers = {
  ...(productTags.some((tag) =&gt;
    collectionName.toLowerCase().includes(tag.toLowerCase())
  ) &amp;&amp; {
    newProduct: &quot;yes&quot;,
  }),
};

console.log(headers);
英文:

You've got your check back-to-front... &quot;product&quot; does not contain (include) &quot;e23product32&quot; but &quot;e23product32&quot; does contain &quot;product&quot;

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

const productTags = [&quot;product&quot;];

const collectionName = &quot;e23product32&quot;;

const headers = {
  ...(productTags.some((tag) =&gt;
    collectionName.toLowerCase().includes(tag.toLowerCase())
  ) &amp;&amp; {
    newProduct: &quot;yes&quot;,
  }),
};

console.log(headers);

<!-- end snippet -->

huangapple
  • 本文由 发表于 2023年5月22日 15:28:01
  • 转载请务必保留本文链接:https://go.coder-hub.com/76303873.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定