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

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

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.

  1. const productTags = [
  2. "product"
  3. ];
  4. const collectionName = 'e23product32';
  5. const headers = {
  6. ...(productTags.some((tag) => tag.includes(collectionName)) && {
  7. "newProduct": "yes",
  8. }),
  9. };
  10. 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 -->

  1. const productTags = [
  2. &quot;product&quot;
  3. ];
  4. const collectionName = &#39;e23product32&#39;;
  5. const headers = {
  6. ...(productTags.some((tag) =&gt; tag.includes(collectionName)) &amp;&amp; {
  7. &quot;newProduct&quot;: &quot;yes&quot;,
  8. }),
  9. };
  10. console.log(headers);

<!-- end snippet -->

答案1

得分: 1

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

  1. const productTags = [&quot;product&quot;];
  2. const collectionName = &quot;e23product32&quot;;
  3. const headers = {
  4. ...(productTags.some((tag) =&gt;
  5. collectionName.toLowerCase().includes(tag.toLowerCase())
  6. ) &amp;&amp; {
  7. newProduct: &quot;yes&quot;,
  8. }),
  9. };
  10. 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 -->

  1. const productTags = [&quot;product&quot;];
  2. const collectionName = &quot;e23product32&quot;;
  3. const headers = {
  4. ...(productTags.some((tag) =&gt;
  5. collectionName.toLowerCase().includes(tag.toLowerCase())
  6. ) &amp;&amp; {
  7. newProduct: &quot;yes&quot;,
  8. }),
  9. };
  10. 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:

确定