remove the attributes of elements in the string [duplicate]

In JavaScript, I am using the below regex to replace the attributes of the elements with empty value. But it is not working.

msg="<p> This news is all about <a title='article' href='https://jhd-dev786.adbcmsq.net/2021/11/blog-11.html' target='_blank'>main</a> content of the  <strong> section  </strong>  </p>n"

 msg = msg.replace(/s?w+='[^']+'s?/, "");

How to access the cookies of the source or the parent domain in which the iFrame is loaded with different domain?

I want to read/access the cookies of the domain ( which is not owned/managed by me ) under which the iFrame of my website domain is loaded.

Let’s take an example

  • The main source/parent domain is – abc.com ( not owned by me )
  • On abc.com there is an iframe with src pqr.com (owned/managed by me )

I want to read the cookies of abc.com(main website) in pqr.com(iframe website)

Is this possible? if yes, how? If not, why?

RegEx-exact word match but case insensitive

Can you tell me how to get the exact word match but case insensitive? I have tried this. But it is not working. Any clue, please?

forEach(keywordsClone, (k) => {

        const regExpression = new RegExp('^' + `${k}` + '$', 'i'); //exact match and case insensitive
    
        transcript = transcript.replace(regExpression, '<span class="color-dark-red">$1</span>');
      });

e.g. let’s say keywordsClone has Fire and transcript has fire. then it should be picked. i.e. true If keywordsClone has Fire and transcript has firee then it should be false.

Marker Clustering from google maps

I am trying to create a google map with selected locations grouped into clusters, I download locations from the database via php/Ajax. Everything works great, markers add’s up, but clusters don’t. I must have missed something … any help, sugestions?

my js code belowe

//code

let map;
let locations=[];
var nowa = [];

function initMap() {
  map = new google.maps.Map(document.getElementById("map"), {
    mapId: '57981e8fa66decba',
    center: { lat: 54.372158, lng: 18.638306 },
    zoom: 12,
    streetViewControl: false,
    fullscreenControl: false,
    mapTypeControl: false,
  });

const infoWindow = new google.maps.InfoWindow({
    content: "",
    disableAutoPan: true,
  });


laduj();
function laduj(){
var xhr = new XMLHttpRequest();
xhr.open('GET', 'coordinates.php?q=', true);
xhr.send(); //wysyła zapytanie
xhr.onload = function(){ //co ma zrobić po otrzymaniu danych
var dane = this.responseText;
testy = JSON.parse(dane);

for(var x = 0; x<testy.length;x++){
var a = testy[x][0];
var b = parseFloat(a);
var c = testy[x][1];
var d = parseFloat(c);
locations.push({lat: b , lng: d});
}

// Add some markers to the map.

for (var j = 0; j<testy.length;j++){
      var marker = new google.maps.Marker({
      position: new google.maps.LatLng(locations[j]),
      map,
    })

nowa.push(marker);
    };
const markerCluster = new markerClusterer.MarkerClusterer({ map, nowa });
  // Add a marker clusterer to manage the markers.


  }
 }
}

Gsap scrolltriger does not work with Bootstrap

I am using vue3, bootstrap 5, and gsap.

I put cdn in my code and applied bootstrap.

However, gsap’s scroll trigger does not work properly.

It works well if I remove start from scrollrigger.create or bootstrap cdn from index.html

If I comment like this, the scroll trigger works well

ScrollTrigger.create({
    // start: '10%',
    end: '100%',
    onUpdate: (self) => {
      self.direction === -1 ? showGoTop.play() : showGoTop.reverse()
    }
  })

or

<!-- <link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> -->

If the annotation is removed, it does not work again.

After applying the bootstrap, the scroll trigger did not work.

What’s wrong with gsap’s start and end?

ASCII value of a character [closed]

ASCII value of a character
Tags: Type Cast
Given a character, find the ASCII value of it.
e.g. Some characters and their ASCII values
‘A’ – 65
‘Z’ – 90
‘p’ – 112
‘2’ – 50
and so on.

Input:
D

Output:
68

D’s ASCII value is 68.

Google Map Route Coverage Calculation

We are into Vehcile Tracking System, and stuck into 1 development phase. Where we have created a Route for a vehcile to use throughout journey. But sometime driver use different paths instead defined one. So we need to calculate the coverage %, how much driver covered from the specified route path.

Below is FeatureCollection for Defined route:

geoJson: {type: "FeatureCollection", features: [{,…}]}
features: [{,…}]
0: {,…}
geometry: {type: "LineString",…}
properties: {Bcolor: "#FF0000", FillColor: "#FF0000", Oemid: "10", strokeColor: "#FF0000", strokeOpacity: "4.0",…}
type: "Feature"
type: "FeatureCollection"

And below is covered area coordinates:

latLong: [[77.02575, 28.44825], [77.02578166666666, 28.448081666666667],…]
[0 … 99]
0: [77.02575, 28.44825]
1: [77.02578166666666, 28.448081666666667]
2: [77.02589166666667, 28.448046666666666]
3: [77.026025, 28.448031666666665]
4: [77.026075, 28.447993333333333]
5: [77.026125, 28.447908333333334]
6: [77.02616, 28.447871666666668]

So need assistance, how to calculate covered percentage from defined route. Tried to understand Google distance api but nothing worked.

How to pass data from vanilla JavaScript to React functional comonent

I’m trying to update (setState) a React functional component from within “regular” (vanilla) JavaScript.

I searched through StackOverflow but all the answers deal with passing data from React to (vanilla) JavaScript, and not the other way around.

Let’s take the example from the docs:

import React, { useState } from 'react';

function Example() {
  // Declare a new state variable, which we'll call "count"
  const [count, setCount] = useState(0);

  return (
    <div>
      <p>You clicked {count} times</p>
      <button onClick={() => setCount(count + 1)}>
        Click me
      </button>
    </div>
  );
}

To render it in JavaScript, I do:

<script>
    let example = ReactDOM.render(
        <Example />,
        document.getElementById('example-wrapper')
    );
</script>

Now suppose I want to manually update the count from the vanilla JavaScript code, outside of react. Like:

<script>
    function updateExampleCount(newCount) {
        example.setCount(newCount);   // ???
    }
</script>

I can’t access the component state, as setCount is a private variable inside the function, and example returned from render is null.

If I use a class component, then render returns a reference to the component and then I can call example.setState. But I prefer not to convert my component into a class if I can avoid it.

The docs for render say:

Render a React element into the DOM in the supplied container and return a reference to the component (or returns null for stateless components).

But my component does have a state (count), it just doesn’t recognize it.
If it’s not possible to use the return value from render, is there another way to “get” the component and then use setCount (or some other way to set the state)?

Or do I just have to use a class component for this?

Thanks.

Uncaught Error: Unable to find node on an unmounted component (react-dom)

i’m writing a webapp using mern stack and while i’m writing the code i got this error and have no idea where this error are occurred.
details about error down below

Uncaught Error: Unable to find node on an unmounted component.
at findCurrentFiberUsingSlowPath (react-dom.development.js:4303)
at findCurrentHostFiber (react-dom.development.js:4465)
at findHostInstanceWithWarning (react-dom.development.js:25389)
at Object.findDOMNode (react-dom.development.js:26067)
at Trigger._this.getRootDomNode (index.js:237)
at Trigger._this.attachParent (index.js:331)
at index.js:349
at callRef (raf.js:36)
at raf.js:40

and this is the only file i change before change this whole application work properly i think this is the file that above error occurred

import React, { Fragment, useState, useEffect } from "react";
import Pagination from 'react-js-pagination';
import { useParams } from 'react-router-dom';
import Slider from 'rc-slider';
import 'rc-slider/assets/index.css';

import MetaData from "./layout/MetaData";
import Product from "./product/Product";
import Loader from "./layout/Loader";

import { useDispatch, useSelector } from "react-redux";
import { useAlert } from "react-alert";
import { getProducts } from "../actions/productActions";

const { createSliderWithTooltip } = Slider
const Range = createSliderWithTooltip(Slider.Range)

const Home = () => {
const [currentPage, setCurrentPage] = useState(1)
const [price, setPrice] = useState([1, 1000])
const [category, setCategory] = useState('')

const categories = [
    'books',
    'pencils',
    'cuters',
    'pastles',
    'Electronics',
    'Headphones',
    'Accessories',
    'Cameras',
    'Laptops',
    'Food'
]

const alert = useAlert();
const dispatch = useDispatch();
const params = useParams();

const { loading, products, error, productCount, resPerPage } = useSelector(
    (state) => state.products
);

const keyword = params.keyword

useEffect(() => {
    if (error) {
        return alert.error(error);
    }

    dispatch(getProducts(keyword, currentPage, price, category));

}, [dispatch, alert, error, keyword, currentPage, price, category]);

function setCurrentPageNo(pageNumber) {
    setCurrentPage(pageNumber)
}

return (
    <Fragment>
        {loading ? (
            <Loader />
        ) : (
            <Fragment>
                <MetaData title={"Home page"} />

                <h1 id="products_heading">Latest Products</h1>

                <section id="products" className="container mt-5">
                    <div className="row">
                        {keyword ? (
                            <Fragment>
                                <div className="col-6 col-md-3 mt-5 mb-5">
                                    <div className="px-5">
                                        <Range
                                            marks={{
                                                1: `$1`,
                                                1000: `$1000`
                                            }}
                                            min={1}
                                            max={1000}
                                            defaultValue={[1, 1000]}
                                            tipFormatter={value => `$${value}`}
                                            tipProps={{
                                                placement: "top",
                                                visible: true
                                            }}
                                            value={price}
                                            onChange={price => setPrice(price)}
                                        />

                                        <hr className="my-5" />

                                        <div className="mt-5">
                                            <h4 className="mb-3">
                                                Categories
                                            </h4>

                                            <ul className="pl-0">
                                                {categories.map(category => (
                                                    <li
                                                        style={{
                                                            cursor: "pointer",
                                                            listStyleType: "none"
                                                        }}
                                                        key={category}
                                                        onClick={() => setCategory(category)}
                                                    >
                                                        {category}
                                                    </li>
                                                ))}
                                            </ul>
                                        </div>
                                    </div>
                                </div>

                                <div className="col-6 col-md-9">
                                    <div className="row">
                                        {products.map((product) => (
                                            <Product key={product._id} product={product} col={4} />
                                        ))}
                                    </div>
                                </div>
                            </Fragment>
                        ) : (
                            products.map((product) => (
                                <Product key={product._id} product={product} col={3} />
                            ))
                        )}

                    </div>
                </section>

                {resPerPage <= productCount && (
                    <div className="d-flex justify-content-center mt-5">
                        <Pagination
                            acvitePage={currentPage}
                            itemsCountPerPage={resPerPage}
                            totalItemsCount={productCount}
                            onChange={setCurrentPageNo}
                            nextPageText={'Next'}
                            prevPageText={'Prev'}
                            firstPageText={'First'}
                            lastPageText={'Last'}
                            itemClass="page-item"
                            linkClass="page-link"
                        />
                    </div>
                )}
            </Fragment>
        )}
    </Fragment>
);
};

export default Home;

and this is the git repo if you want more info check last commit

Can a navbar and a jumbotron share the same background image?

I know it is possible to set the body{background-image) while having them both be transparent. But using this method I cannot set the background-color for the rest of the website.

Is it possible, Using Bootstrap, for the navbar and the jumbotron to share a backround image, while the rest of the website can use a background-color?

Why is my Swiper render buggy at the first time render using React

I’m using React and trying to fetch some of my anime into the home banner using Swiper

I don’t know why when I refresh my page, it’ll only render at half of the swiper.

Here’s how it display:

First display

However, if I press the next or back button, it’ll display normally again.

Working fine after next/previous button being pressed

Here’s my code in my Home Component:

import { useState, useEffect } from "react"
import ReactHlsPlayer from 'react-hls-player';
import './home.css'
import { supabase } from '../../supabaseClient'
import { Swiper, SwiperSlide } from 'swiper/react'
import SwiperCore, { Pagination,Navigation } from 'swiper';
import 'swiper/css'

SwiperCore.use([Pagination,Navigation]);
function Home(){
    useEffect(async ()=>{
        fetchAnime()
    }, [])
    const [animeDetail, setAnimeDetail] = useState([])
    async function fetchAnime() {
        const { data } = await supabase
            .from ('anime')
            .select ()
            setAnimeDetail(data)
    }

    return (
        <>
        <div className="spacer">
            &nbsp;
        </div>
        <div className="home-section">
            <h2>Home Page</h2>
            <Swiper 
            centeredSlides={true}
            slidesPerView={7}
            spaceBetween={10}
            loop={true}
            pagination={false} 
            navigation={true} className="mySwiper">
                {animeDetail.map((element, i)=> 
                    (
                    <SwiperSlide key = {i}><img src={element.anime_image}/></SwiperSlide>
                    )
                    )}

            </Swiper>
        </div>
        </>
    )

}
export default Home

And here’s my Home CSS, sorry if it’s a bit messy, I’m still trying it here and there, but I’m stuck.

  .swiper {
    width: 100%;
    height: 100%;
    margin-left: auto;
    margin-right: auto;
  }
  .swiper-wrapper{
    width: 100%
  }
  .swiper-slide {
    text-align: center;
    font-size: 18px;
    display: flex;
    justify-content: center;
    align-items: center;
    max-width: 280px;
  }
  .swiper-slide img {
    display: block;
    box-sizing: border-box;
    border: none;
    max-height: 350px;
    min-height: 350px;
    -o-object-fit: cover;
       object-fit: cover;
    transition: all .3s ease;
    opacity: 0.5
  }

  .swiper-slide-active {
    transform: scale(1.2);
    z-index: 2
  }
  .swiper-slide-active img{
    transition: all .3 ease;
    opacity: 1
  }

And if someone figures it out, please help me a bit, I tried to whenever the item in the middle is in active, it’ll pop out bigger, but I can’t do it with transform: scale(number) – I have tried it (It does get bigger when it’s active but it doesn’t display bigger at the height, I haven’t figured it out some ways at the moment)

How can I half the array

I am learning to code and I am trying out this javascript object method course. I am currently stuck on this method. I want to have the array with three different numbers(10,20,5) to be /2. I do not understand why it is returning NaN. Thank you for reading.

shirtPrice = 10
jeanPrice = 20
shoePrice = 5

shoppingList = [shirtPrice,jeanPrice,shoePrice];

const shoppingDiscountDay = {
  discountedItems: {
    calculateItemsDiscount() {
        return shoppingList/2; //return NaN
    },
  }
}
console.log(shoppingDiscountDay.discountedItems.calculateItemsDiscount());

How to combine map and clamp function together

There are two functions

const clamp = (num, a, b) => Math.max(Math.min(num, Math.max(a, b)), Math.min(a, b));
const map = (x, a, b, c, d, clamp) => (x - a) * (d - c) / (b - a) + c

const c = map(-50, 0, 1, 0, 100)
const _c = clamp(c, 0, 1)
console.log(_c, c)

Is there any way that the two function could be combined, something like

const _c = map(-50, 0, 1, 0, 100, {clamp: true})

so that I don’t need copy parameters from the map function to get the new value within the parameters range.