Change color of line graph in Highchart.js

I have to create line graph like the below image. When Actual value exceeding Plan value line color should be green otherwise line color should be red in same line graph using below value lstMonth
:
Array(48)
0
:
Actual
:
“74”
Chart_Code
:
“SACLS&MOver AllR0”
From
:
null
GraphModel
:
null
GraphTitle
:
“Overall Achievement ”
GraphType
:
“”
Graph_Better
:
“1”
Graph_Better2
:
“0”
Id
:
null
Last_Year_Actual
:
“99”
Month
:
“Apr”
PageNo
:
“3”
Plan
:
“100”
Plan_revised
:
“”
Policy_Ref_No
:
“OverAll”
Responsible
:
“SL”
Revision_No
:
“0”
ScissorType
:
“0”
To
:
null
UOM
:
“%”
Variance
:
“”
pagetitle
:
null
[[Prototype]]
:
Object
1
:
{Id: null, Policy_Ref_No: ‘OverAll’, Chart_Code: ‘SACLS&MOver AllR0’, Month: ‘May’, Plan: ‘100’, …}
2
:
{Id: null, Policy_Ref_No: ‘OverAll’, Chart_Code: ‘SACLS&MOver AllR0’, Month: ‘Jun’, Plan: ‘100’, …}
3
:
{Id: null, Policy_Ref_No: ‘OverAll’, Chart_Code: ‘SACLS&MOver AllR0’, Month: ‘Jul’, Plan: ‘100’, …}
4
:
{Id: null, Policy_Ref_No: ‘OverAll’, Chart_Code: ‘SACLS&MOver AllR0’, Month: ‘Aug’, Plan: ‘100’, …}
5
:
{Id: null, Policy_Ref_No: ‘OverAll’, Chart_Code: ‘SACLS&MOver AllR0’, Month: ‘Sep’, Plan: ‘100’, …}
6
:
{Id: null, Policy_Ref_No: ‘OverAll’, Chart_Code: ‘SACLS&MOver AllR0’, Month: ‘Oct’, Plan: ‘100’, …}
7
:
{Id: null, Policy_Ref_No: ‘OverAll’, Chart_Code: ‘SACLS&MOver AllR0’, Month: ‘Nov’, Plan: ‘100’, …}
8
:
{Id: null, Policy_Ref_No: ‘OverAll’, Chart_Code: ‘SACLS&MOver AllR0’, Month: ‘Dec’, Plan: ‘100’, …}
9
:
{Id: null, Policy_Ref_No: ‘OverAll’, Chart_Code: ‘SACLS&MOver AllR0’, Month: ‘Jan’, Plan: ‘100’, …}
10
:
{Id: null, Policy_Ref_No: ‘OverAll’, Chart_Code: ‘SACLS&MOver AllR0’, Month: ‘Feb’, Plan: ‘100’, …}
11
:
{Id: null, Policy_Ref_No: ‘OverAll’, Chart_Code: ‘SACLS&MOver AllR0’, Month: ‘Mar’, Plan: ‘100’, …}

change the background color of focused (middle ) slide in swiper.js

I am made a slider using html CSS and swipper.js. i want the color of the focused (middle ) slide is black and other slides are blue how can i do that. i tried but the it is not working properly it change the color of middle slide when i slide the middle slide not when it is in middle position( means when i change the position of middle slide then its color changes to black not when it is in middle position)

    <!DOCTYPE html>
<html lang="en">

    

  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Fody Slider</title>
    <link rel="stylesheet" href="https://unpkg.com/swiper@8/swiper-bundle.min.css" />
    <link rel="stylesheet" href="style copy.css">
    <!-- <link rel="stylesheet" href="styles.css"> -->

  </head>

  <body>
    <div style="width: 100%;height: 200px;display: flex;flex-direction: column;justify-content: center;align-items: center;">
      <p class="prjectsfirsttext">Our Design Process</p>
      <p class="prjectssecondtext">Our Work Process 
          Make Your Dream True</p>
    </div>
    <div style="margin-left: 200px;margin-right: 200px;position: relative; ;display: flex;flex-direction: column;justify-content: center;align-items: center;background-color: white;" id="tranding" >
      <!-- happy clients -->
      
    
      <div class="container1" style="display: flex;justify-content: center;align-items: center;">
        <div class=" "  >
          <button class="swiper-button-prev" style="width: 100px;height: 50px;text-align: center;background-color: red ;border: none;">prev</button>
        </div>
        <div class="swiper tranding-slider swiper-container" style="width: 500px;height: 300px;">
          
          <div class="swiper-wrapper" style="position: absolute;">
            <!-- Slide-start -->
           
            <!-- Slide-end -->
            <!-- Slide-start -->
            <div class="swiper-slide tranding-slide" style="background-color: blue;">
              
            </div>
            <!-- Slide-end -->
            <!-- Slide-start -->
            <div class="swiper-slide tranding-slide" style="background-color: green;">
              
            </div>
            <!-- Slide-end -->
            <!-- Slide-start -->
            <div class="swiper-slide tranding-slide" style="background-color: yellowgreen;">
              
            </div>
            <!-- Slide-end -->
            <!-- Slide-start -->
          
            <!-- Slide-end -->
          </div>
        </div>
        <div class=" " style="bottom: 20px;">
          <button class="swiper-button-next" style="width: 100px;height: 50px;text-align: center;background-color: red ;border: none;">prev</button>
        
        </div>
      </div>
    <!-- </section> -->
  </div>

    <script type="module" src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.esm.js"></script>
    <script nomodule src="https://unpkg.com/[email protected]/dist/ionicons/ionicons.js"></script>
    <script src="https://unpkg.com/swiper@8/swiper-bundle.min.js"></script>
    <script src="script.js"></script>
  </body>

</html>

CSS:

    .container1{
  width: 100%;
  
}


.section-heading {
  font-size: 3rem;
  color: var(--primary);
  padding: 2rem 0;
}

#tranding {
  padding: 4rem 0;
}
.maindpslidercontaner{
  background-color: red;
  padding: 20px;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  border-radius: 10px;
  
}
.maindpslidercontaner img{
    
  width: 80px;
  height: 80px;
}
.maindpslidercontaner :nth-child(2){
  height: 30px;
  margin: 20px;
  color: white;
  font-size: 24px;
  font-weight: bold;

}
.maindpslidercontaner :nth-child(3){
  
  margin: 0px;
  text-align: center;
}


#tranding .tranding-slider {
  height: 52rem;
  padding: 2rem 0;
}



.tranding-slide .tranding-slide-content {
  position: absolute;
  left: 0;
  top: 0;
  right: 0;
  bottom: 0;
}



.swiper-slide-shadow-left,
.swiper-slide-shadow-right {
  display: none;
}

.tranding-slider-control {
  position: absolute;
  top: 50%;
  transform: translateY(-50%);
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

index.js

document.addEventListener("DOMContentLoaded", function () {
  var TrandingSlider = new Swiper('.tranding-slider', {
    effect: 'coverflow',
    grabCursor: true,
    centeredSlides: true,
    loop: true,
    slidesPerView: 2, // Show three slides at a time
    spaceBetween: 0,
    coverflowEffect: {
      rotate: 0,
      stretch: 0,
      depth: 100,
      outerWidth: 200,
      modifier: 2.5,
    },
    navigation: {
      nextEl: '.swiper-button-next',
      prevEl: '.swiper-button-prev',
    },
    on: {
      slideChange: function () {
        updateSlideColors();
      }
    }
  });

  function updateSlideColors() {
  var slides = document.querySelectorAll('.tranding-slide');
  slides.forEach(function (slide) {
    slide.style.backgroundColor = 'blue'; // Set your default background color here
  });

  var activeSlide = document.querySelector('.tranding-slide.swiper-slide-active');
  if (activeSlide) {
    activeSlide.style.backgroundColor = 'black'; // Set background color for active slide
  }
}


  // Initial setup
  updateSlideColors();
});
swiper.on('slideChange', () => {
  const colors = ['#f00', '#0f0', '#00f'];
  const activeSlideIndex = swiper.activeSlide;
  const activeSlide = document.querySelector(`.swiper-slide:nth-child(${activeSlideIndex + 1})`);
  activeSlide.style.backgroundColor = colors[activeSlideIndex];
});

also told me what is the way to I implemented the code of js for purpose so that the focused slide (slide at middle) should black and other should blue but it is not working as aspected how to correct this

now let me show the code of website frontend where i integrated this slider but it is not working

index.html


 

Cant render a react component from onClick

i’m working on a React web app. I would like to render a component from an onClick. So a user looking through profiles should be able to click on a profile and that directs them to the profile/portfolio page. The profiles are mapped through and the onClick is in a map. The code doesn’t work though, the profile prop that’s passed down is undefined. profiles and profile information is pulled from Firestore.

Page With Multiple Profiles

return (
<div>
            {profiles.map((profile) => {
              const portfolioShow = (profile) => {
                console.log("Portfolio Show: ", profile.user);
                navigate(`/portfolio/${profile.user}`);
                return <Portfolio profile={profile} />;
              };

              return (
                <div
                  key={profile.user}
                  onClick={() => portfolioShow(profile)}
                >
                  // Components that show different profiles.
                </div>
)

The Portfolio Show console log works and it prints the profile.user.

The Portfolio page:

export default function Portfolio({ profile }) {
  useEffect(() => {
    console.log("Profile: ", profile);
  }, [publish, profile]);


  return (
          <>
            // portfolio and profile components
          </>
  );
}

The profile prop that’s passed down is undefined.

Any assistance would be appreciated.

React Big Calendar – Custom week view content not showing after upgrading the library

I have just upgraded my React Big Calendar library because I upgraded my Node version and my React Version. So I upgraded from “0.29.0” to “1.8.5”, which I know is a very big jump.

I created a custom weekly view, because I had some functionalities that I wanted to implement, which is to choose the number of days shown in a week. So I implemented it as such:

import PropTypes from "prop-types";
import React, { useEffect, useMemo, useState } from "react";
import Week from "react-big-calendar/lib/Week";
import TimeGrid from "react-big-calendar/lib/TimeGrid";
import { useSelector } from "react-redux";
import dayjs from "dayjs";

function workWeekRange(date, options, daysArray) {
  return Week.range(date, options).filter((d) =>
    (daysArray ?? [0, 1, 2, 3, 4, 5, 6]).includes(d.getDay()),
  );
}

const CustomWeekView = (extraProps) => {
  const [viewConfig, selectedView] = useSelector((state) => [
    state.calendarReducer.viewConfig,
    state.calendarReducer.selectedView,
  ]);
  const { isShowWeekend, numOfDays } = viewConfig;

  const [rerender, setRerender] = useState(false);

  const daysArray = useMemo(() => {
    const today = new Date().getDay();
    const days = [0, 6];

    let startingPoint = today;
    while (startingPoint + numOfDays > 6) {
      startingPoint -= 1;
    }
    for (let i = 0; i < numOfDays; i++) {
      days.splice(i + 1, 0, startingPoint + i);
    }

    return isShowWeekend ? days : days.filter((day) => day !== 0 && day !== 6);
  }, [isShowWeekend, numOfDays]);

  const timeIndicator = document.getElementsByClassName(
    "rbc-current-time-indicator",
  )[0];

  useEffect(() => {
    const updateTimeIndicator = () => {
      if (timeIndicator) {
        const nDayOfWeek = dayjs().day();
        let left;
        let width;

        const index = daysArray.indexOf(nDayOfWeek);
        const targetNum = daysArray.slice(0, index).length;
        left = targetNum * -100;
        width = daysArray.length * 100;

        timeIndicator.style.setProperty("--width", `${width}%`);
        timeIndicator.style.setProperty("--left", `${left}%`);
      }
    };

    updateTimeIndicator();
    setRerender(!rerender);
  }, [selectedView, timeIndicator, daysArray]);

  let { date, ...props } = extraProps;
  let range = workWeekRange(date, props, daysArray);

  return <TimeGrid {...props} range={range} />;
};

CustomWeekView.propTypes = {
  date: PropTypes.instanceOf(Date).isRequired,
};
CustomWeekView.defaultProps = TimeGrid.defaultProps;
CustomWeekView.range = workWeekRange;
CustomWeekView.navigate = Week.navigate;
CustomWeekView.title = (date, { localizer }) => {
  let [start, ...rest] = workWeekRange(date, { localizer });
  return localizer.format({ start, end: rest.pop() }, "dayRangeHeaderFormat");
};
export default CustomWeekView;

This worked fine until I upgraded to “1.8.5”, where the header is showing just fine, but the content and the gutter column are not showing, I could see my events on it, but the background and everything just disappeared. If I tried turning it back to the original week view, then it works fine, but it works without my intended functionality. Is there a change I’m not aware of regarding <TimeGrid /> component maybe or what did I miss?

Here’s a screenshot:
Screenshot

While integrating Firebase firestore into an electron app, I’m getting an error Uncaught ReferenceError: require is not defined

I’m trying to integrate Firebase Firestore into my electron app, however when I import the Firestore module into my views I get an error uncaught ReferenceError: require is not defined.

enter image description here

Here’s my Webpack config

const path = require('path');

module.exports = {
  mode: 'development',
  entry: './src/js/index.js',
  devtool: 'inline-source-map',
  target: 'electron-renderer',
  module: {
    rules: [
      {
        test: /.js$/,
        exclude: /node_modules/,
        use: {
          loader: 'babel-loader',
          options: {
            presets: [[
              '@babel/preset-env', {
                targets: {
                  esmodules: true
                },
                modules: false, // This is important for handling ESM syntax
              }],
              '@babel/preset-react']
          }
        }
      },
      {
        test: [/.s[ac]ss$/i, /.css$/i],
        use: [
          // Creates `style` nodes from JS strings
          'style-loader',
          // Translates CSS into CommonJS
          'css-loader',
          // Compiles Sass to CSS
          'sass-loader',
        ],
      }
    ]
  },
  plugins: [],
  resolve: {
    extensions: ['.js'],
  },
  output: {
    filename: 'app.js',
    path: path.resolve(__dirname, 'build', 'js'),
  },
};

firebase initialization

// Import the functions you need from the SDKs you need
import { initializeApp } from 'firebase/app';
import { getStorage } from "firebase/storage";
import { getFirestore } from "firebase/firestore";



const config = {
  
};

// Initialize Firebase
const App =  initializeApp(config);

const db = getFirestore(App);

export default db;

Data fetching

import { collection, getDocs } from "firebase/firestore";
import db from "../db/firestore";

export const fetchChats = async () => {
    try {
        const chatsCol = collection(db, 'chats');
        const chatsSnapShots = await getDocs(chatsCol);
        
        const chats = chatsSnapShots.docs.map(doc => doc.data());

        return chats;
    } catch (error) {
        console.error("Error fetching chats:", error);
      
    }
}

when I try to import the module fetchChats to another module the app breaks and I get the error above.

Drag event not firing

The drag event is not firing.

const items = document.querySelectorAll(".item");

items.forEach((item) => {
  item.addEventListener("drag", (e) => {
    e.preventDefault();
    console.log(item);
    item.classList.add("dragging");
  });
});
.list {
  display: flex;
  column-gap: 1rem;
}

.item {
  width: 50px;
  height: 50px;
  background-color: red;
}

.item.dragging {
  background-color: blue;
}
<div class="list">
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
  <div class="item"></div>
</div>

I wanted it to set a class on being dragged but it didn;t even fire. I also added a preventDefault() method but that didn’t work either.

Converting a.co links to amazon full links in javascript

I have this piece of code for my website

function extractASIN(link) {
  const asinMatch = link.match(//(?:dp|gp/product|exec/obidos|aw/d)/(B[0-9A-Z]{9}|w{10})|a.co/(?:[^/]+/)?(w{7})(/|?|#|$)/);
  console.log('Link:', link);
  console.log('Match:', asinMatch);
  if (asinMatch) {
    return asinMatch[1] || asinMatch[2];
  } else {
    return '';
  }
}

when using the output from a a.co link I expect to get the product to pop up but instead i tend to always get redirected to the homepage of amazon and was wondering if there was a way to convert the a.co to amazon.ca

how to call parent componet function on button click in reactjs?

I am trying to call parent function on button click . I am not aware how to achieve this .

parent component

export default function Message({ component }) {
  const [state, setState] = useState(false);

  const showMessage = ({ component }) => {
    setState(true);
  };
  return (
    <div>
      {component}
      {state ? <div>Message</div> : null}
    </div>
  );
}
 

now I am using this parent component .

import Message from "./message";

const EmbendComp = () => {
  const onClick = () => {
    alert("oooo");
  };
  return (
    <div className="App">
      <h1>Component</h1>
      <button onClick={onClick}>show Message</button>
    </div>
  );
};

export default function App() {
  return (
    <>
      <Message component={<EmbendComp />} />
    </>
  );
}

I want to call “showMessage” function on button click ..is it possible ? I want to “text” on button click..

here is my code
https://codesandbox.io/s/dazzling-gates-257xgw?file=/src/App.js:23-380

Show/hide content depending on the value of the text field

How can I simplify the code to include all functionalities in one script? Creating separate scripts probably doesn’t make sense 🙂 I would be very grateful for your help.

document.querySelector('#country').addEventListener('change', function calculate(e) {
const div = document.querySelector('#US');
    if (Number(e.target.value) == 1)
    div.style.display = 'block';
  else
    div.style.display = 'none';
});
</script>

<script type="text/javascript">
document.querySelector('#country').addEventListener('change', function calculate(e) {
const div = document.querySelector('#DE');
    if (Number(e.target.value) == 3)
    div.style.display = 'block';
  else
    div.style.display = 'none';
});
</script>

<script type="text/javascript">
document.querySelector('#country').addEventListener('change', function calculate(e) {
const div = document.querySelector('#IT');
    if (Number(e.target.value) == 5)
    div.style.display = 'block';
  else
    div.style.display = 'none';
});
<input type="number" id="country" value="0" size="1" maxlength="1">

<div id="US" class="flag_US" style="display:none;">United States</div>
<div id="DE" class="flag_DE" style="display:none;">Germany</div>
<div id="IT" class="flag_IT" style="display:none;">Italy</div>

Next js route from axios interceptors – Invalid hook call. Hooks can only be called inside of the body of a function component

I am trying to add an Axios api interceptor to route the page to default login page if there is no access token.

import axios from 'axios';
import { useRouter } from 'next/navigation'

const router = useRouter();

const api = axios.create({
    baseURL: 'https://eventsapi.umapps.in',
  });
api.interceptors.request.use(
    (config) => {
          // check if token is available
          const accessToken = localStorage.getItem('accessToken');
          if(!accessToken)
          router.push('/')
          return Promise.reject("Login to continue!!");
    },
    (error) => {
        return Promise.reject(error);
    }
);

export default api;

I am getting the below error with the above code.

Unhandled Runtime Error
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.

Couldn’t find a proper solution. Any inputs on how to fix this will be much helpful. Thanks!

What’s the difference between these two JS codes in V8?

I try to create a codeCache via V8. Use ScriptCompiler::CreateCodeCache function.

ScriptCompiler::CachedData* CreateCachedData(Local<String> sourceContent, Local<String> sourceName) {
    ScriptOrigin* scriptOriginPtr = nullptr;
    scriptOriginPtr = new ScriptOrigin(
            String::NewFromTwoByte(isolate_, sourceName, NewStringType::kNormal).ToLocalChecked(),
            Integer::New(isolate_, 0), Integer::New(isolate_, 0));
    ScriptCompiler::Source* source = nullptr;
    source = new ScriptCompiler::Source(sourceContent, *scriptOriginPtr);

    Local<Script> script;
    ScriptCompiler::Compile(context_, source, ScriptCompiler::CompileOptions::kEagerCompile).ToLocal(&script);

    ScriptCompiler::CachedData* data = ScriptCompiler::CreateCodeCache(script->GetUnboundScript());

    return data;
}

When I use these code, the value of data is nullptr.

function A() {
    "use asm"
    function R() {}
    return R
}

When I use these code, the value of data isn’t nullptr.

function A() {
    "use asm"
    function R() {};
    return R
}

What’s the difference between these two JS codes in V8 or in JS?

Js can’t get info from fetching

So I’m trying to create a small molarity concentration calculator for my lab, which has some chemicals we often use. When I try to fetch the chemicals.json, the web can fetch the JSON file but can not process the calculation.
How

<!DOCTYPE html>
<html lang="en">
    
<head>
    <meta charset="UTF-8">
    <title>ChemistryTools</title>
</head>
    
<body>
    <h1>莫耳濃度計算器</h1>
    <label for="chemical_select">選擇化學物質:</label>
    <select id="chemical_select">
        <option value="APTES">APTES</option>
        <option value="Cyclopropylamine">Cyclopropylamine</option>
    </select><br><br>
    <label for="solvent_volume">溶劑體積 (ml):</label>
    <input type="number" id="solvent_volume" placeholder="輸入溶劑體積"><br><br>
    <label for="solution_concentration">溶液濃度 (mM):</label>
    <input type="number" id="solution_concentration" placeholder="輸入溶液濃度"><br><br>
    <button onclick="calculateChemical()">計算</button><br><br>
    <p id="chemical_use">需加入化學物質 (ul): </p>

    <script>
        function calculateChemical() {
            var selectedChemical = document.getElementById("chemical_select").value;
            var solventVolume = parseFloat(document.getElementById("solvent_volume").value);
            var solutionConcentration = parseFloat(document.getElementById("solution_concentration").value);

            fetch('chemicals.json')
                .then(response => response.json())
                .then(data => {
                    var chemicals = data;

                    if (chemicals[selectedChemical] && chemicals[selectedChemical]['Mweight'] !== undefined && chemicals[selectedChemical]['Density'] !== undefined) {
                        var chemicalMw = chemicals[selectedChemical]['Mweight'];
                        var chemicalDensity = chemicals[selectedChemical]['Density'];

                        var chemicalUseInMl = (solutionConcentration * solventVolume * chemicalMw) / (chemicalDensity * 1000000 - solutionConcentration * chemicalMw);
                        var chemicalUseInUl = (chemicalUseInMl * 1000).toFixed(2);

                        document.getElementById("chemical_use").innerText = "需加入化學物質 (" + selectedChemical + "):" + chemicalUseInUl + " ul";
                    } else {
                        console.error('無法找到化學物質資訊');
                    }
                })
                .catch(error => console.error('Fetch Error:', error));
        }
    </script>
    
</body>
</html>

I added an if/else function to see what’s wrong with the code, and it shows that “無法找到化學物質資訊” which means Could not find out chemical information.

Mocking es6 imported default module with Jest

I am writing a test for a function sendEmail that uses npm package @sendgrid/mail. I’d like to mock @sendgrid/mail in my function and then make assertions on the mocked functions, but for some reason I can’t get my code to use the mocked version. The version imported in the test is always the real one, and the actual module is used in my sendEmail.

Based on the docs it seems like

import { jest } from '@jest/globals';
import sgMail from '@sendgrid/mail';
import { sendEmail } from './functions.js';

jest.mock('@sendgrid/mail');
describe('functions.js', () => {
  test('email subject is generated correctly', async () => {
    console.log(sgMail);

    await sendEmail('test');
    // expect(sgMail.send).toHaveBeenCalledWith('hi');
  });
});

I have tried:

  • providing factory functions
  • using manual mocks in __mocks__ instead.
  • Looking at several examples on github,nothing seems too far from what I am doing.
  • adding testEnvironment: 'jest-environment-node', like https://stackoverflow.com/a/52816572/4541769
  • I have even tried random babel voodoo as described in this question of dubious age to be relevant,
  • as well as the __esModule: true, property which doesn’t seem to be required in my case as I’m not using both default and named modules.

I don’t think this is a sendgrid issue as I have the same problem with Google secret manager. Is there something in my configuration I’m missing? I know I’ve written similar tests before, but can’t spot the difference.

Define a character class and reference it in RegExp literal

I have a character class that I want to use multiple times without copy-pasting it. So, turning something like:

let s = 'Hello, James_1234'
let re = /Hello, [wd-_]+/
console.log(re.test(s)) // => true

Into something more like:

let s = 'Hello, James_1234'
let legalNameChars = /[wd-_]/

let re = /Hello, @{legalNameChars}+/
console.log(re.test(s))

Obviously the above code does not work, because that’s string interpolation syntax and is not applicable here. I am also aware that I could convert everything to strings and back—I would like to interpolate them directly in regex literals if possible.

Why isn’t my h3 element content matching with the array contents?

i am trying to make a script that changes the link of an image to a new image within a div if the h2 element contains any of the text within the array const targetTexts. there is an issue with the if statement, if i remove the part && targetTexts.includes(h3Element.textContent.toLowerCase(), which i need to check against the words in the array, and leave it as and leave it as if (h3Element) , it works and replaces every single image with the new image. but, i need to check the contents of the h2 element against the array so i need that line.

the h3 element textContent outputs stuff like this : “Beauty in motion Attractive young mixed race woman in jeans shirt shaking her head and smiling while standing outdoors, Generative AI 29139243 Stock Photo at Vecteezy”
so i dont get why its not working if there is matches


setTimeout(() => {
  console.log('SCRIPT BEGINS RUNNING');
  // select all search results
  const results = document.querySelectorAll('div[jsname="N9Xkfe"]');
  const aiImg = 'https://www.shutterstock.com/image-vector/anti-ai-sign-no-aigenerated-600nw-2289609093.jpg';
  console.log(results);

  // array of targeted text
  const targetTexts = [
    'ai', 'ai generated', 'generate ai', 'ai art',
    'stable diffusion', 'midjourney', 'generative ai',
    'ai-generated'
  ];

  // loop through each result element
  results.forEach(result => {
    // check if the element has an h2 child with targeted text
    const h3Element = result.querySelector('h3');
    console.log('H3 ELEMENT' + h3Element.textContent);
    console.log('FOR EACH LOOP BEGINS');

    if (h3Element && targetTexts.includes(h3Element.textContent.toLowerCase())) {
      // get the img element and replace the link
      console.log('THE H2 ELEMENT EXISTS!!!');
      const imgSrc = result.querySelector('img');
      console.log('IMAGE SRC: ' + imgSrc);
      imgSrc.setAttribute('src', aiImg);
    }

    console.log('FOR EACH LOOP ENDS');

  });

  console.log('END OF SCRIPT');
}, 2000);

and here is an example of the console logs which i used to confirm i was selecting the correct elements:

enter image description here