How can I use a for loop to check if a string contains multiple letters? [duplicate]

I have written a function that uses a for loop to check each character in a string to see whether it is equal to “a”, and push any letters that are not equal to “a” into an array.

I’m wondering how I can use the bang operator with multiple characters to check these too.
I have tried adding a comma in between strings – if (s[i] !== "a", "b") and this is not working. I’ve been searching for twenty minutes and have found includes(), but I haven’t been able to make it work as anything I find seems to only be able to check one property at a time.

Are there any ways in which I can check for multiple characters / letters in a string?

function printerError(s) {
  let  totalErrors = [];
  for (let i = 0; i < s.length; i++) {
    if (s[i] !== "a") {
      totalErrors.push(s[i]);
    }
  }
  return totalErrors;
}

printerError("abc");

how to convert the output of html text input to a number in javascript

I am trying to make an program which will add two number and i am a beginner i got my stored in a variable but cannot convert it to number

var num1 = Number.parseInt(num0) 

i tried using parse int but i still dont get the correct input

heres my full code

<html>

<body>
  <input type="text" id="text" placeholder="Number 1"></input>
  <input type="text" id="text2" placeholder="Number 2"></input>
  <button type="submit" id="submit" onclick="put()">Click Me</button>
  <p id="myp"></p>
  <script>


    function put() {
      var num0 = document.getElementById("text")
      var num1 = Number.parseInt(num0)
      var num4 = document.getElementById("text2")
      var num2 = Number.parseInt(num4)
      var sub = document.getElementById("submit")
      var res = num1 + num2
      document.getElementById("myp").innerHTML = num1.value + num2.value
    }
  </script>

</body>

</html>

enter image description here

if i try num1.value its undefined and if only try num1 its considered as text

how to check available times in a table to make an appointment? [closed]

    Table MYSQL: Booking
    ┌────┬───────────────┬────────────┬───────────┬───────────┬─────────────┐
    │ ID │ Schedule Date │ Start Time │ End Time  │ Service   │ Client Name │
    ├────┼───────────────┼────────────┼───────────┼───────────┼─────────────┤
    │  1 │ 02/12/2022    │ 13:00      │ 14:00     │ Service 3 │ Connan      │
    │  2 │ 02/12/2022    │ 14:00      │ 14:30     │ Service 2 │ Dean        │
    │  3 │ 02/12/2022    │ 15:00      │ 15:15     │ Service 1 │ Holmes      │
    │  4 │ 02/12/2022    │ 15:30      │ 16:30     │ Service 3 │ Hyuk        │
    └────┴───────────────┴────────────┴───────────┴───────────┴─────────────┘

    Table MYSQL: Services
    ┌────┬──────────────┬──────────┐
    │ ID │ Service Name │ Duration │
    ├────┼──────────────┼──────────┤
    │  1 │ Service 1    │ 0:15     │
    │  2 │ Service 2    │ 0:30     │
    │  3 │ Service 3    │ 1:00     │
    └────┴──────────────┴──────────┘

    Example:

    Service 1 can be scheduled at 15:15.
    Because: Interval beteween 15:15 and 15:30 is 15 minutes,
    making the 15:15 available to book a service with 0:15 minutes duration.

WHAT I WANT TO DO:

  1. I want to create a check by service, so if the customer chooses to schedule service 1, it will be checked in the Booking table which times are available to make the appointment (Perhaps calculating the difference between the End Time and Start Time of the next appointment or obtain the duration of the service from the table services) , as mentioned in the example, if service 1 were chosen, the time of 15:15 would be available. And finally, display 3 or more time options to schedule.

INTENTIONS OF USE
It’s a bot, where the customer receives options for the services they want to schedule, and the bot checks which times are available and schedules them. (for more information)

Does Javascript support any special syntax to support performance testing?

I need to track how long many processes take and so my code looks like this:

console.log("Doing thing 1");
var startTime = performance.now();
var thing = doThing()
times.loadTime = performance.now() - startTime;

console.log("Doing thing 2");
startTime = performance.now();
var thing2 = doOtherThing();
var endTime = performance.now();
times.thingTime2 = endTime - startTime;

console.log("Doing thing 3");
var thing3 = doThing3();
ties.thingTime3 = performance.now() - endTime;

As you can guess, this is getting hard to read.

I know that in my current environment I can use things like:

console.startTime();
console.startTime("Thing 1");
console.endTime();

And so on. See the console object.

But I think I’ve seen something where javascript code was using blocks or labels like this:

thing1 {
   var thing = doThing()
}

thing2 {
    var thing2 = doOtherThing();
}

thing3 {
    var thing3 = doThing3();
}

// desired result { name: "thing1", startTime: 0, endTime: 10 }
console.log(thing1);

Or labels:

thing1:
    var thing = doThing()
end

These look much more readable to me.

Is there a way to do this in JavaScript?

How to get value of editor in nextjs

I am new in Reacjs and i am working with nextjs, Right now i am trying to save form data using axios (Api), I want to get value of editor, And i want to upload image using API Also, How can i do this ?Here is my current code

      const handleSubmit = (e: any) => {
        e.preventDefault();
         const data = {
            first: e.target.name.value,
            last: e.target.cat_name.value,   //Right now getting title,cat_name
          }

          //My axios api code here
      };

Here is editor and file code

<div className="form-group">
                    <label>File upload</label>
                    <input
                      type="file"
                      name="file"
                      className="file-upload-default"
                    />


                    <div className="input-group col-xs-12">
                      <input
                        type="text"
                        className="form-control file-upload-info"
                        
                        placeholder="Upload Image"
                      />
                      <span className="input-group-append">
                        <button
                          className="file-upload-browse btn btn-primary"
                          type="button"
                        >
                          Upload
                        </button>
                      </span>
                    </div>
                  </div>


                  
<Editor
         onInit={(evt, editor) =>  editor}
         initialValue="<p>This is the initial content of the editor.</p>"
         init={{
           height: 500,
           menubar: false,
           plugins: [
             'advlist autolink lists link image charmap print preview anchor',
             'searchreplace visualblocks code fullscreen',
             'insertdatetime media table paste code help wordcount'
           ],
           toolbar: 'undo redo | formatselect | ' +
           'bold italic backcolor | alignleft aligncenter ' +
           'alignright alignjustify | bullist numlist outdent indent | ' +
           'removeformat | help',
           content_style: 'body { font-family:Helvetica,Arial,sans-serif; font-size:14px }'
         }}
       />

How to add an SVG circle to an Array of SVGs in react on button click

import { useState, useRef } from 'react'
import './App.css'

function App() {
  const [circle, setCircle] = useState([])
  const refElement = useRef(null);

  const width = 500;
  const height = 500;
  const circleX= Math.floor(Math.random() * 400);
  const circleY = Math.floor(Math.random() * 400);
  const circleRadius = 20;
  const randomColor = '#' + (Math.random().toString(16) + "000000").substring(2,8)

  const LeadCircle = <circle cx={circleX} cy={circleY} r={circleRadius} fill={randomColor} stroke={"black"} strokeWidth={"10"}/>
  const Circle =  <circle cx={circleX} cy={circleY} r={circleRadius} fill={randomColor}/>


  const addLead = () =>{
    console.log("circleLead added " + LeadCircle)
    LeadCircle
    setCircle(previous =>[...circle,previous]);

  }

  const addNormal = () =>{
    console.log("circleNormal added " + Circle)
  }
  
  const removeLast = () =>{
    
  }
  const removeAll = () =>{
    
  }


  return (
    <div className="App">
      <h1>doobverse setup with svg</h1>
      <div className="card">
      <div id="svg-container">
        <svg width={width} height={height} style={{border:"2px solid white"}} useref={refElement}> 
        {LeadCircle}
        </svg>
      </div>
        <br></br>
        <br></br>
        <button id={"addLead"} onClick={addLead}>
          Add lead
        </button>
        <button onClick={addNormal}>
          Add normal
        </button>
        <br></br><br></br>
        <button onClick={removeLast}>
          remove one
        </button>
        <button onClick={removeAll}>
          remove all
        </button>
      </div>
    </div>
  )
}

export default App

So thats my Code,

I just want to have a simple React app, where you can add a circle on button click, remove the last drawn circle, and remove all drawn circles… Ive tried to do this with canvas before. I could draw circles on click but had Problems removing them, so I have asked in a Discord where they explained me that you need to clear and redraw the canvas every time you want to remove an element and that its easier to work with svgs, so I’ve set the thing up with svgs but now its not even working with the add function…

Thx for help !!

🙂

Using localstorage to save workout progress

I’m creating a workout app using html css and javascript. when i get to displaying and saving the workout progress of user, then it seem impossible. Please, is there anyone who can give me an idea of how to go about it

one the click of a next button the workout should be saved as complete and the next is showed

Making a quiz game in Svelte

I’m making a basic version of the game “Who Wants to be a Millionaire?” using Svelte. I think I have the setup correct thanks to another user on here, but I’m currently having difficulty with a specific aspect.

The flow of the program should go like this:

Click the start button & the content of the button changes to a question.
The answer fields below the question get populated with possible answers.
There’s a predetermined answer to each, when the right answer is clicked, it moves to the next question in the sequence.
If the wrong question is picked, the game simply ends with the start button content changed to “GAME OVER.”
Below is a copy of my code thus far, I’ve done my best to do a writeup:

<script>
  //Initial definition of all my data.
  let data = {
    question: "Start Game",
    options: ["Option 1", "Option 2", "option 3", "option 4"],
  };
  let selectedOption = "";
  //Function that ends the game.
  function endGame() {
    data.question = "GAME OVER";
  }
  //Question functions: Each populates the data array with the question and answers.
  function question1() {
    data.question = "What game is this?";
    data.options = ["Deal or No Deal", "Chess", "Who Wants to Be a Millionaire?", "Halo 3",
    ];
// MY ATTEMPT TO PROGRESS THE FIRST QUESTION TO THE NEXT.
    if (document.querySelector("#ans_3").click) {
      question2;
    } else {
      endGame;
    }
  }
  function question2() {
    data.question = "What is the answer to this question?";
    data.options = ["Not this one", "This one", "Not this one", "Not this one"];
    if (document.querySelector("#ans_2").click) {
    }
  }
</script>

<!-- HTML starts here. (In svelte) -->
<title>Who Wants to Be a Millionaire?</title>
<body>
  <div class="container">
    <h2 class="title">Who Wants to Be a Millionaire?</h2>
    <p>
      Click the start game button to begin. The game ends when you get a
      question wrong.
    </p>
    <p>You can see your winning on the board to the right.</p>
    <div class="game-div">
      <div class="question-container">
        <!-- Start button doubles as the question field. Starts the first question onclick. -->
        <button class="startButton" on:click={question1}>{data.question}</button>
        <!-- Dynamic options objects created below. -->
        <div class="option-container">
          {#each data.options as option, idx}
            <label>
              <input
                id={"ans_" + idx}
                type="radio"
                bind:group={selectedOption}
                name="scoops"
                value={option}
              />
              {option}
            </label>
          {/each}
        </div>
      </div>
    </div>
  </div>
</body>

I’m primarily trying to make it so answering the first question actually initiates the second one. I’m not quite sure how to do this. I’ve marked my attempt above.

.some with e.target.dataset.id returns false but hardcoded value returns true

pokemonContainer.addEventListener('click', function (e) {
  let favourite = getStorageItem('pokemon');
  let eTargetID = e.target.dataset.id;
  let found = favourite.some((el) => el.id === eTargetID);
  console.log(found);
  console.log(eTargetID);
  if (!found) {
    favourite.push(pokemonArray[e.target.dataset.id - 1]);
    setStorageItem('pokemon', favourite);
  }
});

I’m trying to look for an id inside an array with objects. The object have an id of 1. My e.target.dataset.id is 1 but it returns false. But when I hardcode the value el.id === 1, it returns true. Am I doing something wrong? Why is it false even though e.target.dataset.id is also 1?

How to loop if invalid input in prompt

For the final input, your program prompts the user for their year of study. Once again, this is not a
required field, that is, a default value of 1 (as in 1st year of study) should be submitted if the user chooses
to leave this field blank. Additionally, you must validate the data the user provides (if provided) to ensure
that it is not less than 1, and not greater than 3 (valid range is 1-3 years of study).

If your solution detects invalid input, your program must loop to allow the user to re-enter year of study,
this process continues indefinitely, until valid input is detected.


I have tried a few different methods and this is my most recent attempt, but after 5 hours, I needed to ask for help. Code is below ( Yes, I’m a noob 🙁 )

do {
   var yearofStudy = prompt("Please enter your Year of Study", "1")
    console.log(yearofStudy)
    }
while
    ( yearofStudy > 1 && yearofStudy <4 )

Weird unexpected token error when trying to name a class

I am trying to name a class in Javascript and when I initialize the class it has an error at the name of the class.

class e {.  //SyntaxError: Unexpected token (13:6)
  constructor(name, damage) {
    this.name = name;
    this.damage = damage;
  }
}

Also, if I make another, identical in everything but name, class under it then there is no error on the second class.

class e { //SyntaxError: Unexpected token (13:6)
  constructor(name, damage) {
    this.name = name;
    this.damage = damage;
  }
}

class a { //all that comes up here is that a is not called in my program
  constructor(and, what) {
    this.and = and;
    this.what = what;
  }
}

When I add a third class nothing happens to the second class, no errors are coming up. So I have no idea why this is happening.

This is for a school project and we are using Code.org’s App Lab if that makes a difference.

I copied a class from another program that works and pasted it into this program and changed only the names, hoping that error would go away, but the error still is there.

How to throttle/debounce function inside of React useEvent hook?

Note that useEvent is still in the proposal stage, but is available for use today through the react-use-event-hook package.


Unfortunately it doesn’t seem like it’s possible to properly throttle a function inside of useEvent, but I’d really like to be shown that I’m wrong.

I guess we need to throttle the function somewhere else? But then if we need to do that from the same functional component, then useEvent is pretty grievously limited.

localStorage storaging JSON as [object Object]

When I try to use localStorage to store an JSON it becomes a [object Object], here is the code

const treino = [
  { A: "Costas e Biceps" },
  { B: "Membros inferiores e Ombro" },
  { C: "Peito e Triceps" }
];

const treinoJSON = JSON.stringify(treino);

localStorage.setItem("papa", treino);

const treinoJSONSaved = localStorage.getItem("papa");

const treinoJSONSavedParsed = JSON.parse(treinoJSONSaved);

console.log(treinoJSONSavedParsed);

I’ve tried to “console.log” every step and the variable becomes a JSON with no problem, if I parse it outside of the localStorage it works just fine, but when I store it doesn’t work.

image loads but does not update

I have little experience with javascript, I’m trying to make the image update but I’m not succeeding. This image comes through an API, But the image is not updating

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<script type="text/javascript">

 function atualizarqr() {
  document.getElementById("img").src = "<?= $this->admin_m->qr_whatsapp(); ?>";
}

window.onload = function () {
  setInterval(atualizarqr(), 5000);
};
</script>


<div onload="atualizarqr">
<img src="" id="img"/>
</div>