Replace entire input string according to format of replacement string?

I’m working on a piece of code to allow users to perform dynamic regular expression replacements of strings. The primary “mode of operation” is intended to be as follows:

  • User enters a search string which includes capture-groups ((foo))
  • User enters a replacement string which includes capture-group references ($1, $2, …)
  • The final output string follows the format of the replacement string exactly (somewhat comparable to printf string formatting in C), as opposed to the “format” of the search string.

It means, for example, that the following parameters should give the respective output:

Search: (abc) xyz (123)
Replacement: $1 - $2
Output: abc - 123

I do realize that, in this instance, simply adding .* to the beginning and end of the Search parameter would essentially accomplish just this, but would also require manipulating the user input, which seems like not the best idea and prone to breaking with something as complex as regex, in some scenarios anyway.

So I was wondering if there are any internal utlity functions/methods readily available in JavaScript to safely perform this kind of regex string transformation? I looked around for a while, but maybe I’m just not using the right keywords…

Replace a part of a Timestamps (YYYY-MM-DD) in relation to another columns YYYY-MM-DD using either node js or bigquery SQL

So as shown in the BigQuery table, start_date, end_date, expected_start_date, and expected_end_date are all timestamp types. I want to have the expected_start_date and expected_end_date to have the same YEARS-MONTH-DAYS (only those 3 not hours minutes seconds) as there respective start_date and end_date in the same row.

For example, that first row has a start_date of 2022-06-16 09:19:18.433729 UTC and a expected_start_date of 2022-07-08 04:00:00 UTC. I want the expected_start_date to have the same date as the start_date like this 2022-06-16 04:00:00 UTC. Is there anyway I can replace just the expected_start_date years months and days in relation to the start_dates years months and days with timestamp types using either node.js (javascript) or bigquery sql. Same thing I want to be applied to the expected_end_date and end_date.

BigQuery table screenshot

How To Get Interest And APR Based On Monthly Payment, Loan Term, Total Loan Amount?

I am trying to get the interest rate and APR in javascript for the following:

Payment = 340 Per Month
Loan Amount = 16000 Total
Term Of Loan = 72 Months

Also The payment on the loan never changes, it will remain 340 per month for the life of the loan.

Any help with this would be greatly appreciated. Thank you. I would include a code sample but I am no where near close to solving this.

why is onClick() triggered twice when rending the buttons using map() [duplicate]

I am new to frontend and I am trying to implement a simple feature where:
retrieve a list of cities, render a button for each city and catch the click action of them individually

I am getting the list like this:

this.state.favCts: ['Sydney', 'melbourne', 'tokyo', 'bankok']

and rendering the buttons like this

<div className="column">
                    {this.state.favCts.map(
                        (item, index) => 
                             <button key={index} onClick = {console.log("show fav city" + item)}>{item}</button>
                    )}
</div>

however the buttons will be clicked twice when they are being rendered, and won’t log anything if I click them afterwards

How to grab specific values from a list that has primitives

I am new to JS and have a really annoying problem. I am using a combination of Karate UI (sister of Selenium WebDriver) and JS to write tests for a website.

Scenario: I have a table where I am trying to iteratively go through each row that matches my expected text and grab a particular column value for that row.

I am using a native Karate command to grab all values that match my criteria. The problem is, the command often yields a list of primitives. Mine looks something like this:

Write  123 1.0.1.8 TargetProduct1       P1 10.0 en-US
Write  4586 1.0.1.3 TargetProduct5      Test2 10.1  en-US
Write  134 1.0.1.1 TargetProduct0       Four2 10.3  en-US
Write  3 1.0.1.2 TargetProduct2     Boo3 10.1   en-US

What I would like to do is, extract sixth column values into an array (P1, Test2, Four2, Boo3). Historically I have been able to grab values using Object.Keys. However, since this is a list, I cannot do Keys. I have tried Object.Values and it also does not work.

Please advise. Thank you in advance!

PS- I already asked the question on the Karate forum and there was no answer, so that is why I am not tagging it here.

Get all elements of class but group by siblings

Is there a simple way to select all elements of a class, but group them by siblings?

For example:

<div class="main-div">
    <div class="get-this"></div>
    <div class="get-this"></div>
    <div class="get-this"></div>
    <div class="sub-div">
        <div class="get-this"></div>
        <div class="get-this"></div>
    </div>
</div>
<div class="get-this"></div>
<div class="get-this"></div>
<div class="get-this"></div>

If I wanted to get all the elements of class get-this but wanted to loop through the elements that are siblings like in main-div, sub-div and outside of any div separately without assigning a separate class? I can’t think of a good way to do this without traversing the entire DOM.

Javascript DOM not detecting button from ID, says its null

I am working for theodinproject, and doing the library project, I am trying to access each of my forms value when I press a button, however, when trying to define the element in Javascript, it says in the website console,
“Uncaught TypeError: submit is null”(my button is called submit)
I presume the error is with the fact that i hide the form, and only show it when i clicked a button, the form contains the bad submit button.
here is my code:
html:

<!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">
  <link rel="stylesheet" href="./style.css">
  <script src="./script.js" defer></script>
  <title>Library</title>
</head>
<body>
  <div class="title">Library</div>
</body>
<div class="container">
  <div class="addBtn">
    <button id = 'add'>Add Book</button>
  </div>
  <div class="grid">
  </div>
  <div class="form" id = 'form'>
    <form>
      <div class="titleBook">
        <label for="bookTitle">Title</label>
        <br>
        <input type="text" id="bookTitle" required>
      </div>
      <div class="Author">
        <label for="bookAuthor">Author</label>
        <br>
        <input type="text" id="bookAuthor" required>
      </div>
      <div class="pages">
        <label for="bookPages">Num of Pages</label>
        <br>
        <input type="number" id="bookPages" required>
      </div>
      <div class="readCheck">
        <input type="checkbox" id="bookRead" name = 'isRead' value="read">
        <label for="bookRead">Read</label>
      </div>
      <div class="submit">
        <button type="submit" id ='submitBtn'>Submit</button>
      </div>
    </form>
  </div>
</div>
</html>

(ignore empty classes)
css if you need:

@import url('https://fonts.googleapis.com/css2?family=Poppins:wght@300;400;500;700&display=swap');

*{
  margin: 0;
  padding: 0;
  box-sizing: border-box;
  font-family: 'Poppins', sans-serif;
}
.form {
  display: flex;
  justify-content: center;
  position: relative;
  top:15vh;
  height: 400px;
  display: none;
}
form{
  background-color: white;
  padding: 30px;
  border-radius: 15px;
}
form input{
  border: 2px black solid;
  border-radius: 25px;
  padding: 5px;
}
form div{
  margin-bottom: 30px;
}
form button{
  border: 1px solid lightgreen;
  border-radius: 25px;
  background-color: lightgreen;
  width:100px;
  height:35px;
  font-size: 1em;
}
.submit{
  display: flex;
  justify-content: center;
}

.title{
  display: flex;
  justify-content: center;
  font-size: 2.3em;
  background-color: white;
  align-items: center;
  height:10vh;
}
body{
  background-color: rgb(221, 221, 221);
}
.addBtn{
  display: flex;
  justify-content: center;
  align-items: center;
}
#add{
  background-color: lightblue;
  border: 2px solid lightblue;
  border-radius: 25px;
  width:10em;
  height:3em;
  font-size: 1em;
}
#add:hover{
  background-color: white;
  border: 2px solid white;
}
button:hover{
  cursor: pointer;
}
.container{
  width:75vw;
  position: relative;
  left: 15em;
  top:5em;
}

Javascript:

let addBtn = document.getElementById('add');
console.log(addBtn.textContent)
let form = document.getElementById('form')
let body = document.querySelector('body')
let bookTitle = document.querySelector('input#bookTitle').value;
let bookAuthor = document.querySelector('input#bookAuthor').value;
let bookPages = document.querySelector('input#bookPages').value;
let bookRead = document.querySelector('input#bookRead').value;
let submit = document.getElementById('submitBtn');
function Book() {
  this.title = bookTitle;
}
submit.addEventListener('click', () => {
  console.log('reached click');
})

function addBookToLibrary() {
}
addBtn.addEventListener('click', () => {
  form.style.display = 'flex';
})
window.addEventListener('keydown', (e) => {
  if (e.key == 'Escape'){
    form.style.display = 'none';
  }
})

everything works but the submit event listener,
help appreciated

Unable to solve error fetch isn’t defined

I am trying to fetch an API, I tried import fetch from 'node-fetch give me an error (can’t use outside the module), the second thing I tried using const fetch = require('node-fetch') this give me an error fetch isn’t defined, someone kindly helps me out I am unable to figure it out read the documentation still it’s not working as I expected maybe a silly mistake
here is my code

//router file

const express = require('express');
const Router = express.Router();//router will  be used now to route
require('dotenv').config();
const fetch =  require('node-fetch')


Router.get('/', (req, res) => {
    const API_url = 'http://api.open-notify.org/iss-now.json';
    res.render('main');
    fetch(API_url)
    .then(res => res.json())
    .then(data => console.log(data))


})

module.exports = Router;


APP.js file

const express  =  require('express');
const bodyparser = require('body-parser');
const myRouter = require('./routers/router')
const mongoose =  require('mongoose');
const mongodb = require('mongodb')
const ejs = require('ejs');
const app = express();

//setting port
const port = process.env.port || 9090;

app.set('view engine' , 'ejs');
app.use(bodyparser.urlencoded({extended:false}));
app.use(bodyparser.json());
app.use(express.static('public'));
app.use('/',myRouter);


app.listen(port,()=>
{
    console. log(`server is running at http://localhost:${port}`);
})
npm node-fetch is installed
{
  "name": "pridiction_website_complete",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo "Error: no test specified" && exit 1",
    "start": "nodemon app.js"
  },
  "author": "moiz",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.20.0",
    "dotenv": "^16.0.1",
    "ejs": "^3.1.8",
    "express": "^4.18.1",
    "hbs": "^4.2.0",
    "mongodb": "^4.7.0",
    "mongoose": "^6.4.4",
    "node-fetch": "^3.2.8"
  },
  "devDependencies": {
    "nodemon": "^2.0.19"
  }
}

Where are private variables stored within modules/factory functions? or how are they accessed/edited? [duplicate]

const Player = (name, level) => {
  let health = level * 2;
  const getLevel = () => level;
  const getName  = () => name;
  const die = () => {
    // uh oh
  };
  const damage = x => {
    health -= x;
    if (health <= 0) {
      die();
    }
  };
  const attack = enemy => {
    if (level < enemy.getLevel()) {
      damage(1);
      console.log(`${enemy.getName()} has damaged ${name}`);
    }
    if (level >= enemy.getLevel()) {
      enemy.damage(1);
      console.log(`${name} has damaged ${enemy.getName()}`);
    }
  };
  return {attack, damage, getLevel, getName};
};

const jimmie = Player('jim', 10);
const badGuy = Player('jeff', 5);
jimmie.attack(badGuy);

Sorry if this is a dumb/redundant question, I am really struggling with this concept. In the example above, two instances of Player are made using the factory function. Only four of the five methods are returned and the variable ‘health’ is not returned. When we choose to invoke jimmie.attack(badGuy), or jimmie.damage(2) how does javascript know what their health is at? Where is health stored if it didn’t get returned from the function? How do both players have different health levels?
I genuinely would appreciate any help!

discord.js V.13 Embed Issue – RangeError [EMBED_FIELD_NAME]: MessageEmbed field names must be non-empty strings. – Specifically “Member Since:” field

I’m working on a userinfo command in discord.js V.13, but I just can’t seem to get it to work.
The error is centred around my “Member Since:” field.

Photo Error: https://i.imgur.com/65ul9PU.png

Written Error:

if (typeof data !== ‘string’) throw new error(errorMessage);

RangeError [EMBED_FIELD_NAME]: MessageEmbed field names must be non-empty strings.

const { CommandInteraction, Client, MessageEmbed } = require(`discord.js`);
const moment = require("moment");
const emoji = [
    { name: "DISCORD_EMPLOYEE", emoji: "<:Staff:994985083633160272>" },
    { name: "DISCORD_CERTIFIED_MODERATOR", emoji: "<:CertifiedModerator:994985105724551218>" },
    { name: "PARTNERED_SERVER_OWNER", emoji: "<:ServerPartner:994985085780643850>" },
    { name: "HYPESQUARD_EVENTS", emoji: "<:HypeSquardEvents:994985103824523296>" },
    { name: "HOUSE_BRAVERY", emoji: "<:HouseBraveryMember:994985087856820345>" },
    { name: "HOUSE_BRILLIANCE", emoji: "<:HouseBrillianceMember:994985091883348048>" },
    { name: "HOUSE_BALANCE", emoji: "<:HouseBalanceMember:994985089949777920>" },
    { name: "BUGHUNTER_LEVEL_1", emoji: "<:BugHunterLvL1:994985107939147936>" },
    { name: "BUGHUNTER_LEVEL_2", emoji: "<:BigHunterLvL2:994985101580566588>" },
    { name: "EARLY_VERIFIED_BOT_DEVELOPER", emoji: "<:VerifiedDeveloper:994985099135295529>" },
    { name: "EARLY_SUPPORTER", emoji: "<:EarlyNitroSupporter:994985096706801915>" }
  ];

module.exports = {
    name: `userinfo`,
    description: `Get a persons user information`,
    permission: "ADMINISTRATOR",
    usage: "/userinfo [USER]",
    options: [{
        name: 'user',
        type: 'USER',
        description: 'Select a user',
        required: true,
    }],
    /**
     * @param {CommandInteraction} interaction
     * @param {Client} client
     */
    async execute(interaction, client) {
        const user = interaction.options.getUser('user')
        await user.fetch();
        const flags = user.flags.toArray();

        let badges = [];
          emoji.forEach((e) => {
            if (flags.includes(e.name)) badges.push(e.emoji);
          });
        const startMessage = new MessageEmbed()
            .setTitle(`${user.tag}`)
            .setColor("BLURPLE")
            .setDescription(`**Badges:** ${badges.join(" ")}`)
            .setThumbnail(user.avatarURL({ dynamic: true }))
            .addField({ name: 'ID:', value: ````${user.id}```` })
            .addField({ name: "Member Since:", value: ````<t:${parseInt(member.joinedAt / 1000)}:R>````, inline: true })
            .addField('Nickname:', ````${user.nickname || "False"}````, true)
            .addField('Bot Account:', ````${user.bot ? "True" : "False"}````, true)
            .addField('Discriminator:', ````#${user.discriminator}````, true)
            .addField('Nitro:', `${user.premiumSubscriptionCount ? '```Yes```' : '```No```'}`,true)
            .addField("Banner:", `${user.bannerURL() ? "```True```" : "```False```"}`, true)
            .addField('Discord Account Created at:', ````${moment(user.createdAt).format('MMM Do YYYY')}````, true)
            .setImage(user.bannerURL({ dynamic: true, size: 512 }) || "")
        await interaction.reply({ embeds: [startMessage] });
    }
}

(Javascript) Microphone and audio from mediastream are out of sync

I wrote a recorder that records microphone from getUsermedia and audio which is from local using Howler JS.
I created mediastream destination, and
connected each sources (mic, audio) to the destination.
audio seems fine, but microphone is delayed about 2seconds.
I can’t figure out the problem.
could you help me guys?

var recorder;
const stop = document.getElementsByClassName("stop");
const record = document.getElementsByClassName("record");

let mediaDest = Howler.ctx.createMediaStreamDestination();
Howler.masterGain.connect(mediaDest);
function onRecordingReady(e) {
  // 'e' has 'blob event'
  //var audio = document.getElementById("audio");
  audioBlob = e.data; // e.data has blob.
  //audio.src = URL.createObjectURL(e.data);
}

let audioBlob;
let audioURL = "";

navigator.mediaDevices.getUserMedia({ audio: true }).then(function (stream) {
  let userMic = Howler.ctx.createMediaStreamSource(stream);
  userMic.connect(mediaDest);
  Howler.masterGain.connect(mediaDest);
  recorder = new MediaRecorder(mediaDest.stream);
  recorder.addEventListener("dataavailable", onRecordingReady);
  recorder.addEventListener("stop", function () {
    W3Module.convertWebmToMP3(audioBlob).then((mp3blob) => {
      const downloadLink = document.createElement("a");
      downloadLink.href = URL.createObjectURL(mp3blob);
      downloadLink.setAttribute("download", "audio");
      //downloadLink.click();
      var audio = document.getElementById("audio");
      audio.src = URL.createObjectURL(mp3blob);
      console.log(mp3blob);
    });
  });
});

record[0].addEventListener("click", function () {
  recorder.start();
});

stop[0].addEventListener("click", function () {
  recorder.stop();
});

Reactjs – You may need an additional loader to handle the result of these loaders

After deleting the node module and yarn.lock I run yarn install and I dont know why i received this error, please help. Thanks

I used react js for this one.

./node_modules/pdfjs-dist/build/pdf.js 2119:34
Module parse failed: Unexpected token (2119:34)
File was processed with these loaders:
 * ./node_modules/react-scripts/node_modules/babel-loader/lib/index.js  
You may need an additional loader to handle the result of these loaders.
|           async destroy() {
|             this.destroyed = true;
>             await this._transport?.destroy();
|             this._transport = null;
|