Complex string manipulation by JavaScript regexp

I am generating some meaningful name with the following rule in a JavaScript/Node JS program:

Input: “tenancy_account__accountPublicId__workspace__workspacePublicId__remove-user__userPublicId

Expected output: “TenancyAccountAccountPublicIdWorkspaceWorkspacePublicIdRemove-userUserPublicId”

Rules:

  1. replace any character with zero or more underscore to the non-underscored uppercase
    Example:x | __*x => X
  2. If exists remove last _

This is what is tried so far, looking for better alternatives, if any:

const convertBetterString = (input) => {
    const finalString = [];
    if (input && input.includes('_')) {
        const inputStringSeparation = input.split('_');
        if (inputStringSeparation.length > 1) {
            if (inputStringSeparation[inputStringSeparation.length - 1] === '') {
                inputStringSeparation.splice(inputStringSeparation.length - 1, 1);
            }
            inputStringSeparation.forEach((val, index) => {
                if (val === '' && inputStringSeparation[index + 1]) {
                    const actualString = inputStringSeparation[index + 1];
                    const formattedString = actualString.charAt(0).toUpperCase() + actualString.slice(1);
                    finalString.push(formattedString);
                }
            });
            return finalString.length > 0 ? finalString.join('') : inputStringSeparation.join('');
        } else {
            return input.charAt(0).toUpperCase() + input.slice(1);
        }
    } else {
        return input;
    }
}

ochange event only works after the second selection

I have to show some data base on selection drop down list, the form is dynamic, here is my teplates

        function imeiInfo () {    
            $('select').change(function(e) {
                e.stopImmediatePropagation();
                let elm = $(this);
                data = {};
                data[elm.attr("name")] = elm.val();
                $.ajax({
                    url:'/ajax/return_back_imei_plusinfo/',
                    data:data,
                    success:function(data){
                        console.log(data.price)
                        if (data.price){
                            elm.closest("div.child_imeiforms_row").find("input.nrx").val(data.price);
                        }

                        if (data.mobile){
                            elm.closest("div.child_imeiforms_row").find("input.mobile-type").val(data.mobile);
                        }
                    }
                })
            })             
        }
        imeiInfo();
        <form action="" method="POST" id="create-permcustomer-invoice">{% csrf_token %}        
            <div class="row">
                <div class="col-md-6">
                    <div class="form-group">
                    <i class="fas fa-file-signature"></i>
                    <label>customer</label>
                    {{ main_form.customer | add_class:'form-control' }}
                    </div>
                    <p class="text-danger text-center" hidden id="collection_date_error"></p>
                </div>
                <div class="col-md-2">
                    <div class="form-group">
                    <i class="fas fa-box-usd"></i>                        
                    <label>balance</label>
                    <input type="number" disabled class="form-control" id="balance_cus">

                </div>
                    <!-- /.form-group -->
                </div>               
                <!-- /.col -->
                <div class="col-md-4 pull-right">
                    <div class="form-group">
                    <i class="far fa-clock"></i>
                    <label>date</label>
                    {{main_form.created | add_class:'form-control text-center'}}
                    </div>
                    <p class="text-danger text-center" hidden id="company_error"></p>
                    <!-- /.form-group -->
                </div>                 
            </div>   
            <div class="row no-gutters title_info text-center table-bordered text-white">
            </div>         
            {{imei_forms.management_form}}
            <div id="form-imeilists">
                {% for imei in imei_forms %}
                {{imei.id}}
                <div class="child_imeiforms_row">

                    <div class="row no-gutters table-bordered">
                        <div class="col-md-3">
                            <div class="form-group">
                                {{imei.item | add_class:'form-control choose'}}
                                <div class="text-danger text-center" hidden></div>
                            </div>
                        </div>
                        <div class="col-md-3">
                            <div class="form-group">
                                <input type="text" disabled class="form-control mobile-type" placeholder='mobile type '>
                            </div>
                        </div>
                        <div class="col-md-2">
                            <div class="form-group">
                                {{imei.price | add_class:'nrx'}}
                                <div class="text-danger text-center" hidden></div>
                            </div>
                        </div>
                        <div class="col-md-1">
                            <div class="form-group">
                                {{imei.discount | add_class:'dis'}}
                                <div class="text-danger text-center" hidden></div>
                            </div>
                        </div>                                                
                        <div class="col-md-2">
                            <div class="form-group">
                                {{imei.cash | add_class:'cash'}}
                                <div class="text-danger text-center" hidden></div>
                            </div>
                        </div>
                {% endfor %}
            </div>
            <div id="empty-imei-invoiceform" class="hidden">
                <div class="row no-gutters table-bordered">
                    <div class="col-md-3">
                        <div class="form-group">
                            {{imei_forms.empty_form.item | add_class:'form-control choose'}}
                            <div class="text-danger text-center" hidden></div>
                        </div>
                    </div>
                    <div class="col-md-3">
                        <div class="form-group">
                            <input type="text" disabled class="form-control mobile-type" placeholder='mobile type'>
                        </div>
                    </div>
                    <div class="col-md-2">
                        <div class="form-group">
                            {{imei_forms.empty_form.price | add_class:'nrx'}}
                            <div class="text-danger text-center" hidden></div>
                        </div>
                    </div>
                    <div class="col-md-1">
                        <div class="form-group">
                            {{imei_forms.empty_form.discount | add_class:'dis'}}
                            <div class="text-danger text-center" hidden></div>
                        </div>
                    </div>                                                
                    <div class="col-md-2">
                        <div class="form-group">
                            {{imei_forms.empty_form.cash | add_class:'cash'}}
                            <div class="text-danger text-center" hidden></div>
                        </div>
                    </div>
            <button type="button" class="btn btn-lg btn-info" id="add-more-invoice">add new row</button>

            <div class="card-footer">
                <div class="row justify-content-center">
                    <button type="submit" class="btn btn-lg btn-success">save</button>
                </div>
            </div>
        </form>

but it only works well for the first form, after the form, i’ve to select the drop down list in order to return the data !
and here is my views.py

@login_required
def return_back_imei_plusinfo(request):
    query = request.GET
    for item in query:
        if item.startswith("imei-") and item.endswith("-item"):
            item_id = query.get(item)
            break    
    selling_price= Imei.objects.get(id=item_id).mobile.selling_price,
    mobile=Imei.objects.get(id=item_id).mobile.mobile.model,
data = {
    'price' : selling_price,
    'mobile':mobile,
}    
return JsonResponse(data)

and here is my forms.py

class ImeiModelChoiceField(ModelChoiceField):
    def label_from_instance(self,obj):
         return str(obj.imei)

class ImeiInvoiceForm(forms.ModelForm):
    item = ImeiModelChoiceField(queryset=Imei.objects.filter(status=True),widget=forms.Select(attrs={'onchange':'imeiInfo();'}))
    class Meta:
        model = ImeiInvoice
        fields = ['item','price','cash','discount']
        widgets = {
            'price':forms.NumberInput(attrs={'class':'form-control','onkeyup':'totalSum()'}),
            'cash':forms.NumberInput(attrs={'class':'form-control','onkeyup':'totalSum()'}),
            'discount':forms.NumberInput(attrs={'class':'form-control','onkeyup':'totalSum()'}),

    }

is there another way achieve that please !?
thank you in advance ..

How to throw a server error when fetching JS

I’m new in JavaScript and i have a task to post an email input from form to a node server,everything works fine,but i should implement this functionality:
When an email is [email protected], the server responds with the 422 status code and payload which contains the information about the error. Use browser developer tools to examine the response for this scenario. Display the error message in the browser using window.alert().
I created a customException,it gives me the error in the console,but the server still responds with the 200 status code,but as i understand,it should give an error and the post should not work.How to do this task,i have no idea..?
Fetch functions:

import { validateEmail } from './email-validator.js'

export const sendSubscribe = (emailInput) => {
    const isValidEmail = validateEmail(emailInput)
    if (isValidEmail === true) {
        sendData(emailInput);
        // if (emailInput === '[email protected]'){
        //     throw new CustomException('422');
        // }
    }
}

const sendHttpRequest = (method, url, data) => {
    return fetch(url, {
        method: method,
        body: JSON.stringify(data),
        headers: data ? {
            'Content-Type': 'application/json'
        } : {}
    }).then(response => {
        if (response.status >= 400) {
            return response.json().then(errResData => {
                const error = new Error('Something went wrong!');
                error.data = errResData;
                throw error;
            });
        }
        return response.json();
    });
};

const sendData = (emailInput) => {
    sendHttpRequest('POST', 'http://localhost:8080/subscribe', {
        email: emailInput
    }).then(responseData => {
        console.log(responseData);
    }).catch(err => {
        console.log(err, err.data);
    });
}

function CustomException(message) {
    const error = new Error(message);
    error.code = "422";
    window.alert('Forbidden email,please change it!')
    return error;
  }
  
  CustomException.prototype = Object.create(Error.prototype);

Validate function:

const VALID_EMAIL_ENDINGS = ['gmail.com', 'outlook.com', 'yandex.ru']

export const validateEmail = (email) => !!VALID_EMAIL_ENDINGS.some(v => email.includes(v))

export { VALID_EMAIL_ENDINGS as validEnding }

Please help.Thanks in advance!

SetInterval keeps running in webcomponent when element is not present in dom anymore

At the moment, I am working on a simple application that orchestrates multiple webcomponents. One of these components holds a setInterval function. The function keeps running, even when the component itself is not present in the dom anymore. Can one explain to me why this is the case?

Here is a simple reproduction:

const selectorEl = document.getElementsByTagName('body')[0];
selectorEl.innerHTML = '<my-component></my-component>'; // Append custom component to body

class WebComponent extends HTMLElement {
    constructor() {
        super();
        this.innerHTML = '<span>This should not be visible since I am removed instantly!</span>';
        setInterval(() => console.log('I am still running...'), 2000);
    }
}

window.customElements.define('my-component', WebComponent);
selectorEl.innerHTML = ''; // Remove element from the dom directly

Implementing functions [closed]

  • A checkSuspect function that takes a suspect object as parameter from the data structure below. Your function should return a number
    value indicating how many of their properties match the witness
    statement. You should use conditional statements to compare the
    suspect’s properties to the statement.

  • A findGuilty function which traverses the array of suspects and returns the object representing the guilty suspect, otherwise – return
    an empty object.

There are many possible ways of carrying out your duties, but you
should complete this task using ONLY the following commands:

  • function checkSuspect(suspectObj){}
  • function findGuilty(){}
  • if()
Witness statement:

  It was last Thursday, I heard noises outside so I looked out and saw a person in the steet.They seemed to be between the age of 18 and 42 years old.I remember they had a facial tattoo.They were wearing a black overcoat.They brobably weigh between 69 and 74 kg.I 'm not quite sure. They were fairly tall, I think between a height of 155 and 210 cm. It'
s so hard to remember right now.It was very dark and I could barely see, They were carrying a red backpack.I distinctly remember that they were wearing a dotted necktie, I remember thinking that was quite unusual.I 'll never forget their blue eyes. They wore thin metallic glasses. That'
s all I know officer.

  */

var lineupLog = [{
    "name": "ERMELINDA MOHWAWK",
    "glasses": "black",
    "coat": "white fur coat",
    "tattoo": "jellyfish",
    "accessory": "metal briefcase",
    "height": 186,
    "weight": 72,
    "age": 48
  },
  {
    "name": "LARRAINE GOODBURY",
    "glasses": "very thin",
    "coat": "red parka",
    "tattoo": "sword",
    "accessory": "orange plasic bag",
    "height": 181,
    "weight": 80,
    "age": 44
  },
  {
    "name": "MAJORIE WARMAN",
    "glasses": "thin metallic",
    "coat": "black overcoat",
    "tattoo": "facial",
    "accessory": "red backpack",
    "height": 162,
    "weight": 73,
    "age": 30
  },
  {
    "name": "LINETTE TINTLE",
    "glasses": "light tan",
    "coat": "yellow poncho",
    "tattoo": "big arrow",
    "accessory": "orange tote bag",
    "height": 162,
    "weight": 77,
    "age": 35
  },
  {
    "name": "JULIANA OORIN",
    "glasses": "dark brown",
    "coat": "green army coat",
    "tattoo": "anchor",
    "accessory": "laptop bag",
    "height": 170,
    "weight": 81,
    "age": 38
  },
  {
    "name": "JACQUELINE DORCEY",
    "glasses": "red",
    "coat": "green jacket",
    "tattoo": "dark black",
    "accessory": "big black envelope",
    "height": 179,
    "weight": 65,
    "age": 38
  },
  {
    "name": "GAYLA PORTOS",
    "glasses": "white",
    "coat": "blue overcoat",
    "tattoo": "neck",
    "accessory": "black duffle bag",
    "height": 177,
    "weight": 66,
    "age": 55
  }
];

var myFont;
var backgroundImg;

function preload() {
  myFont = loadFont('SpecialElite.ttf');
  backgroundImg = loadImage("Background.png");
}

function setup() {
  createCanvas(640, 480);
  textFont(myFont);
}

// Declare both your functions here





function draw() {
  //You don't need to alter this code
  image(backgroundImg, 0, 0);

  fill(255, 0, 0);
  text(findGuilty().name + " is guilty!", 60, 80);
}

:

  • A checkSuspect function that takes a suspect object as parameter from the data structure below.
    Your function should return a number value indicating how many of their properties match the witness statement.
    You should use conditional statements to compare the suspect’s properties to the statement.

  • A findGuilty function which traverses the array of suspects and returns the object representing the guilty suspect,
    otherwise – return an empty object.

There are many possible ways of carrying out your duties,
but you should complete this task using ONLY the following
commands:

  • function checkSuspect(suspectObj){}
  • function findGuilty(){}
  • if()

How to control the aws-sdk(v3) S3 getSignedUrl format

While using getSignedUrlPromise aws-sdk(v2), I had received a different url format.

Example: https://ddd-bucket.s3.amazonaws.com/blahblah.zip?AWSAccessKeyId=AKIA7&Expires=1598004195&Signature=qJa6oOa7Dc7ni1FmJD

But when I recently moved to aws-sdk v3 and used getSignedUrl, I received a different format

Example:

“https://ddd-bucket.s3.us-east-1.amazonaws.com/blahblah.zip?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Content-Sha256=UNSIGNED-PAYLOAD&X-Amz-Credential=AKIAT7D5SI6FKOVNQPBH%2F20211217%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20211217T104437Z&X-Amz-Expires=7200&X-Amz-Signature=fa86fe9af25e7510b92dd9cdf97fb312bfcb198c6a7868ae09d0a94feb40da99&X-Amz-SignedHeaders=host&x-id=GetObject”

Currently I don’t want these extra headers, I want the previous url which i got using aws-sdk v2?

Is it due passing region while initialising S3Client?

Thank You

Angular11 FrontEnd with js and

im begginer and need help with Angular. I’ve looked for many yt guides and tutorials but everyone says different hting. I’d love to know how to use API and HTTP in Angular11 and how ho connect Js fiel to html.(I’m newbie pls helpo)

Sorting data and its children using Javascript

I have data. There are other data of the same type that have children in this data. I want to sort them all according to their ‘id’ fields, but I couldn’t set up the algorithm scheme for it.

What I’ve tried:

const sortedData: [] = [];

function sortAscending(datas: Group[]) {
    sortedData.push(datas.sort((group1, group2) => (group1.id > group2.id ? 1 : -1)));
    return sortedData;
}

With this code, I can only sort without children.

I tried to model the picture I wanted to describe:
enter image description here

Updating a clip-path in d3.js?

In my recent project, I am interested in creating a clip-path which moves with my mousemove. My initial idea was simply to select and re-position the ellipsis with its attributes cx and cy using the mousemove coordinates, then selecting the rectangle and re-initializing its clip-path attribute.

This, however, does not seem to work. The only workable solution I have found so far is to delete the rectangle and the clip-path, then re-initializing them at the new coordinates. This works fine for the simple test-case below, but in my actual experiment, the object I’ll try to clip is an externally loaded svg, and having to re-load it every mouseover tick might be prohibitively expensive.

Do you have any suggestions on how to achieve the same effect as I have shown below without re-initializing everything?

<!DOCTYPE html>
<html>

  <head>
    <script src="https://unpkg.com/mathjs/lib/browser/math.js"></script>
    <script src="https://d3js.org/d3.v4.min.js"></script>
    
    <style>

    </style>
  </head>

<!-- Create a div where the graph will take place -->
<div id="my_datavisualization">
  <svg id="click" xmlns="http://www.w3.org/2000/svg">
      <defs>
          <g id="pointer" transform="scale(0.5)">
              <circle cx="0" cy="0" r="20" id="dragcircle" />
          </g>
      </defs>
  </svg>
</div>



  <body style='overflow:hidden'>
  
    
    <script>
    
        // Get the viewport height and width
      const vw = Math.max(document.documentElement.clientWidth || 0, window.innerWidth || 0)
      const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0)
      
      // Fit to viewport
      var height            = vw*0.7;
      var width             = vw;
      
      // Create the canvas. We will use only part of it for the main plot
      var svg = d3.select("#click") // This selects the div
          .attr("width", width) // This defines the canvas' width
          .attr("height", height) // This defines the canvas' height
      
      
        
      
      // define the clipPath
      svg.append("clipPath")       // define a clip path
          .attr("id", "ellipse-clip") // give the clipPath an ID
        .append("ellipse")          // shape it as an ellipse
          .attr("cx", 175)         // position the x-centre
          .attr("cy", 100)         // position the y-centre
          .attr("rx", 100)         // set the x radius
          .attr("ry", 50);         // set the y radius

      // draw clipped path on the screen
      svg.append("rect")        // attach a rectangle
          .attr("id","cliprect")
          .attr("x", 125)        // position the left of the rectangle
          .attr("y", 75)         // position the top of the rectangle
          .attr("clip-path", "url(#ellipse-clip)") // clip the rectangle
          .style("fill", "lightgrey")   // fill the clipped path with grey
          .attr("height", 100)    // set the height
          .attr("width", 200);    // set the width
      
      
      // Shift the marker around on mouseover; restrict it to the contour
      var movex
      var movey

      svg
        .on("mousemove", function () {
        
            // Get the current mouseover coordinates
            movex = d3.event.x;
            movey = d3.event.y;

          // The only way I get this to work right now is by removing the previous clipped shape, then re-adding it
          d3.select("#cliprect").remove()
          d3.select("#ellipse-clip").remove()
          
          // define the clipPath
          svg.append("clipPath")       // define a clip path
              .attr("id", "ellipse-clip") // give the clipPath an ID
            .append("ellipse")          // shape it as an ellipse
              .attr("cx", movex)         // position the x-centre
              .attr("cy", movey)         // position the y-centre
              .attr("rx", 100)         // set the x radius
              .attr("ry", 50);         // set the y radius
            
          // draw clipped path on the screen
          svg.append("rect")        // attach a rectangle
              .attr("id","cliprect")
              .attr("x", 125)        // position the left of the rectangle
              .attr("y", 75)         // position the top of the rectangle
              .attr("clip-path", "url(#ellipse-clip)") // clip the rectangle
              .style("fill", "lightgrey")   // fill the clipped path with grey
              .attr("height", 100)    // set the height
              .attr("width", 200);    // set the width
          
          
            
          });

      
  
    </script>
  </body>

</html>

Prevent useState from multiplying eventListeners

I’m trying to create some sort of typing test, making letters be removed from a string if they have been typed correctly. My initial approach was to use a state to save the words in, and if the correct key has been pressed, remove the first letter from the string. However, this results in a lot of bugs, such as that after around 20 correct keys, the function starts to remove multiple characters from the string and when pressed on some keys, the string even starts building itself back, pressing on ‘e’ and ‘r’ in my case. It is not an infinite render, so I’m not sure why. I think what is happening is that the eventlistener is multiplying, so it starts to remove multiple letters, if I’d console log the key pressed this confirms this as well. Here is the code.

    const [words, setWords] = useState("a lot of words are put here")
    const removeLetter = (e) => {
        if (e.key === words[0]) {
            setWords((letters) => letters.substring(1));
    }
    document.addEventListener("keypress", function(e) {removeLetter(e)})

My javascript code doesn’t work, but when it is executed in the console it works

I have a problem, my javascript code does not work, I have an error in the console, but when I paste it in the console, it works perfectly. Somebody could explain me

if (document.getElementById('r1').checked){ 
    document.querySelector('.title-opa-dentals').classList.add('opacity')
};
.opacity{
    opacity: 1!important;
}
<div class="box-slider slides">
    <input type="radio" name="r" id="r1" checked>
    <input type="radio" name="r" id="r2">
    <input type="radio" name="r" id="r3">
    <div class="select-1"></div>
    <div class="select-2"></div>
    <div class="select-3"></div>
    <div class="navigation">
        <label for="r1" class="bar">
        <a class="title-opa-dentals">Dentals</a> 
        </label>
        <label for="r2" class="bar">
        <a class="title-opa-jewellers">Jewellers</a>
        </label>
        <label for="r3" class="bar">
        <a class="title-opa-industrials">Industrials</a>
        </label>
    </div>

How to handle AJAX resquest with express js

I am trying to handle a ajax request using expressjs, when i click the any anchor tag then the page fully reloads and didn’t get the hand ajax request on client side. I need when i click any of these link then it should handle by client side using fetch api

This is html stucture

<header id="main-header">
  <nav>
    <ul>
      <li class="nav-bar"><a data-urlid="" href="/">Home</a></li>
      <li class="nav-bar"><a data-urlid="about" href="/about">About</a></li>
      <li class="nav-bar"><a data-urlid="achievements" href="/achievements">Achievements</a></li>
      <li class="nav-bar"><a data-urlid="gallery" href="/gallery">Gallery</a></li>
      <li class="nav-bar"><a data-urlid="contact" href="/contact">Contact</a></li>
    </ul>
  </nav>  
</header>

This is controller

const home = (req, res) => {
   res.json({message:"success"})
};

this is router for get home page

router.get("/", danceController.home);

Trying to handle ajax request using vanilla js

const navBars = document.querySelectorAll(".nav-bar");

async function head(event) {
  event.preventDefault();
  const url = event.target.dataset.urlid;

    const responseData = await fetch(`/${url}`, {
        method: "GET",
        headers: {"Content-Type":"text/html"}}).then((response) => {
            console.log(response);
        });
    
    // console.log(responseData);
};

for (const navBar of navBars) {
    navBar.addEventListener("click", head)
}

Shopping cart with a selected value in cookie using JavaScript

I need some help with my Shopping Cart. I’m using cookie to create it and my code is working, but there is one thing missing.Right now when I add a couch in my cookie, my cookie looks like this :

[{"colors":["Black/Yellow","Black/Red"],"_id":"415b7cacb65d43b2b5c1ff70f3393ad1","name":"Kanap Cyllène","price":4499,"imageUrl":"http://localhost:3000/images/kanap02.jpeg","description":"Morbi nec erat aliquam, sagittis urna non, laoreet justo. Etiam sit amet interdum diam, at accumsan lectus.","altTxt":"Photo d'un canapé jaune et noir, quattre places"}]

And my console.log gives me this :

[{…}]
0: {colors: Array(2), _id: '415b7cacb65d43b2b5c1ff70f3393ad1', name: 'Kanap Cyllène', price: 4499, imageUrl: 'http://localhost:3000/images/kanap02.jpeg', …}

The user is able to add the couch he selected in the cookie but he has several color options and I want my cookie to take the value selected by the user because for the moment my cookie is an array with the selected couch and in this array there is the array of the several color choices. I tried to simply add the value in my array but it doesn’t work. I tried this :

let couchColor = document.getElementById("colors").value
            if(cart === null) {
                cart = [couch + couchColor]
                console.log(cart)
            }

But with this my cookie doesn’t understand couch anymore and looks like this :

["[object Object]Black/Yellow"]

Can someone help me please ? I want the array of color to be replaced by the value selected by the user. Here is my code :

.then((couch) => {
        let newImage = document.createElement("img");
        newImage.src = couch.imageUrl;
        newImage.alt = couch.altTxt;
        image[0].appendChild(newImage);
        title.innerHTML = couch.name;
        price.innerText = couch.price;
        description.innerText = couch.description;

// Choix couleurs

    
        for (choice in couch.colors) {
            colors.options[colors.options.length] = new Option(
                couch.colors[choice], couch.colors[choice]
            );
        }

// Ajouter produit au panier https://stackoverflow.com/questions/10730362/get-cookie-by-name

        addButton.onclick = ('click', function () {
            let cart = getCookieByName("cart")
            let couchColor = document.getElementById("colors").value
            if(cart === null) {
                cart = [couch + couchColor]
                console.log(cart)
            } else {
                cart = JSON.parse(cart)
                cart.push(couch)
            }
            document.cookie = "cart=" + JSON.stringify(cart)+";"
            })
        })
    }
    
    function getCookieByName(name)
    {
    var match = document.cookie.match(new RegExp('(^| )' + name + '=([^;]+)'));
    if (match) {
        return match[2];
    }
    else{
        return null
    }
}

disabled button not working properly in react

if give more than 10 characters then button should be disabled but when we give <10 character’s button should be enabled not working

import React, { useState } from "react";
export default function DropDown() {
  let [disable,setDisable]=useState(false)
  function check(){
    let inp=document.querySelector('input');
    let btn=document.querySelector('button');
    if(inp.value.length>10){
      btn.disable=true
      setDisable(true)
    }else{
      btn.disable=false;
      setDisable(false)
    }
  }
   return (
    <>
    <input disabled={setDisable} onKeyUp={check}/>
<button>click</button>
    </>
  );
}