Issue Width of header and content is different for same column for data table why this happen?

I work on asp.net MVC I face issue cell header width different from width of cell content details for same column for data table .

so how to make cell header width and cell details content to be same

I make red marks to columns not have same width header and details as request date and Dept.Manager columns and others etc.

I using data table as below my code details as below

<div class="row" style="padding-top: 10px; margin-top: 10px; border: 1px solid black; margin-bottom: 50px; width: 100%; padding-left: 2em; padding-right: 2em;padding-bottom: 2em;">

    <h2 style="margin-left: 5px; margin-top: 40px;">My Requests</h2>

    <table id="dtbl" class="table table-bordered table-hover table-striped" style="width:100%;">
        <thead>
            <tr style="background-color: #f2f2f2;">

                <th style="border: 1px solid black;">
                    Request No

                </th>

                <th style="border: 1px solid black;">
                    Request Date

                </th>
                <th style="border: 1px solid black;">
                    Reason

                </th>
                <th style="border: 1px solid black;">
                    Line Manager

                </th>
                <th style="border: 1px solid black;">
                    Dept.Manager

                </th>
                <th style="border: 1px solid black;">
                    Employee Remarks

                </th>
                <th style="border: 1px solid black;">View Resignation Form</th>
                <th style="border: 1px solid black;">Print(Resignation)</th>

                <th style="border: 1px solid black; display: none">Exit Interview</th>

            </tr>
        </thead>

        <tbody>
            @foreach (var item in Model.MyRequests)
            {
                <tr style="background-color: #f2f2f2;">

                    <td style="border: 1px solid black;">
                        @Html.DisplayFor(modelItem => item.RequestNo)
                    </td>

                    <td style="border: 1px solid black;">
                       
                        @Convert.ToDateTime(item.ResignationSubmissionDate).ToString("dd/MM/yyyy")
                    </td>
                    <td style="border: 1px solid black;">
                        @Html.DisplayFor(modelItem => item.Reason)
                    </td>
                    <td style="border: 1px solid black;">

                        @if (item.LineManagerStatus == "Waiting for Line Manager Approval")
                        {
                            <span>Pending</span>
                        }
                        else if (item.LineManagerStatus == "Rejected by Line Manager")
                        {
                            <span>Rejected</span>
                        }
                        else
                        {
                            @Html.DisplayFor(modelItem => item.LineManagerStatus)
                        }
                    </td>
                    <td style="border: 1px solid black;">
                        @if (item.DirectManagerStatus == "Waiting for Department Head Approval")
                        {
                            <span>Pending</span>
                        }
                        else if (item.DirectManagerStatus == "Rejected by Head Department")
                        {
                            <span>Rejected</span>
                        }
                        else
                        {
                            @Html.DisplayFor(modelItem => item.DirectManagerStatus)
                        }

                    </td>
                    <td style="border: 1px solid black;">
                        @if (item.RevokeRequest == "1")
                        {
                            <span>Cancelled</span>
                        }

                        else
                        {

                        }

                    </td>
                    <td style="border: 1px solid black;">
                        
                    </td>
                    <td style="border: 1px solid black;">

                       

                    </td>

                    <td style="border: 1px solid black; display: none">
                        <a class="exitinterview">Exit Interview</a>

                    </td>

                </tr>
            }
        </tbody>

    </table>
</div>

and on jQuery i do as below

  $(document).ready(function () {
  $('#dtbl').DataTable({
      "scrollX": true,
      "pageLength": 10,
      "dom": 't', // Only show the table without search and other elements
      "language": {
          "search": "", // Empty string to remove the search text
          "searchPlaceholder": "" // Empty string to remove the search input
      },
      initComplete: function () {
          $('.buttons-excel, .buttons-pdf, .buttons-print, .buttons-csv, .buttons-copy').remove();
      }
  });
});

my issue display on image below

cell header and details content not same

Upload file from Azure function to sharepoint list

Im Looking to upload a file from azure functions to a sharepoint list .
Ive heard of Pnp library but im having difficulty pin pointing exactly how to build a function to upload a file .
any assistance in this matter would be appreciate your assistance.
So far i have the azure function and im getting a file from the form in postman

const { app } = require("@azure/functions");
const { BlobServiceClient } = require("@azure/storage-blob");


app.http("httpTrigger1", {
  methods: ["GET", "POST"],
  authLevel: "anonymous",
  handler: async (request, context) => {
    // Use await to resolve the Promise returned by request.formData()

    const formData = await request.formData();

    console.log("Filename: ", formData.get("uploadDoc"));

    const fileContent = await formData.get("uploadDoc").text();

    // console.log(fileContent);
  },
});

I tried import pnp library but keep getting errors while detailing that i cannot use require with this library and that the module is unavailable.

Use Javascript and streamlit to press 5

This is not pressing 5. Please note the code needs to work even if the app is hosted remotely.

import streamlit as st

def main():
st.title("Press 5 Button App")

# Button to trigger JavaScript function
button_clicked = st.button("Press 5")

if button_clicked:
    st.markdown(
        """
        <script>
            // Function to simulate pressing the "5" key
            function simulateKeyPress() {
                var eventObj = document.createEvent("Events");
                eventObj.initEvent("keydown", true, true);
                eventObj.keyCode = 53;
                document.dispatchEvent(eventObj);
            }

            // Call the function when the button is clicked
            simulateKeyPress();
        </script>
        """
    )
    st.success("5 key simulated!")

if __name__ == "__main__":
    main()

POST FormData with Node fetch (Missing headers)

I’m attempting to POST FormData to an API from within my Lambda handler. The solution used to work when done in a similar way with Axios, but fetch will not automatically generate the required headers. The API will deny any request that is missing ‘Content-Type’ (including boundary) and ‘Content-Length’ headers. Here is what my code currently looks like:

const requestData = new FormData();
requestData.append('csv', fs.createReadStream(fileNameWithPath));
requestData.append('currency', currency);

const response = await fetch(url, {
    method: 'POST',
    headers: {
        'Authorization': authToken
    },
    body: requestData
});

I have tried to use form-data-encoder and modified my request as follows:

import {FormDataEncoder} from 'form-data-encoder';
import {Readable} from 'stream';

const requestData= new FormData();
requestData.append('csv', fs.createReadStream(fileNameWithPath));
requestData.append('currency', currency);

const encoder = new FormDataEncoder(requestData);

const response = await fetch(url, {
    method: 'POST',
    headers: {
        'Authorization': authToken,
        ...encoder.headers
    },
    body: requestData
});

… In this instance my requestData size doesn’t match the content-length header. I’ve attempted to use:

body: Readable.from(encoder) like the ReadMe for form-data-encoder suggests, but the fetch body complains that Readable isn’t assignable to type ReadableStream or FormData… Additionally – Will this no longer pass a FormData object to the API? For whatever reason, the API I’m using is extremely particular about incoming requests & their headers.

how can i load the name of display name in individual page

Contact Fetch page contain permission handler and load contacts
show display name and phones Individual page code for each person
I want to show the name of contact person in app bar,
but I do not know how to show it and what to write in display name and i want solve it

Contact fetch code

class Contact Fetch extends StatefulWidget {
  static const String screen route = "Contact Fetch";
  const ContactFetch({super. Key});

  get display Name => null;
  get phones => null;

  @override
  State<ContactFetch> create State() => _Contact State();
}

class _Contact State extends State<ContactFetch> {
  @override
  void initState() {
    super. InitState();
    _ask Permissions();
  }

  Future<void> _ask Permissions() a sync {
    Permission Status permission Status = await _getContactPermission();
    if (permission Status != PermissionStatus.granted) {
      _handleInvalidPermissions(permission Status);
    }
  }

  Future<Permission Status> _getContactPermission() a sync {
    PermissionStatus permission = await Permission.contacts.status;
    if (permission != PermissionStatus.granted &&
        permission != PermissionStatus.permanentlyDenied) {
      PermissionStatus PermissionStatus = await Permission.contacts.request();
      return PermissionStatus;
    } else {
      return permission;
    }
  }

  void _handleInvalidPermissions(PermissionStatus PermissionStatus) {
    if (PermissionStatus == PermissionStatus. Denied) {
      const snack Bar = Snack Bar(content: Text('Access to contact data denied'));
      Scaffold Messenger .of(context).showSnackBar(snack Bar);
    } else if (PermissionStatus == PermissionStatus.permanentlyDenied) {
      const snack Bar =
          Snack Bar(content: Text('Contact data not available on device'));
      Scaffold Messenger. of(context).showSnackBar(snack Bar);
    }
  }
  Future<List<Contact>>? reqContact;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      app Bar: App Bar(
        title: const Text('Contacts List'),
      ),
      body: Column(
        children: [
          Elevated Button(
              on Pressed: () {
                set State(() {
                  req Contact =
                      ContactsService.getContacts() as Future<List<Contact>>?;
                });
              },

              child: const Text("Load Contact")),
          Expanded(
              child: Future Builder(
                  future: reqContact,
                  builder: (context, snp) {
                    if (snp.connectionState == ConnectionState.done) {
                      var contacts = snp. Data;

                      if (contacts != null) {
                        return ListView.builder(
                            shrink-wrap: true,
                            item Count: contacts. length,
                            item Builder: (context, index) {
                              Contact contact = contacts[index];

                              return List Tile(
                                title: Text(' ${contact.displayName}'),
                                leading: Circle Avatar(
                                  child: Text("A"),
                                ),
                                subtitle: Text(contact.phones?.single.value ??
                                    "not found"),
                                on Tap: () {
                                  Navigator.pushNamed(
                                      context, Individualpage.screenroute);
                                },
                              );
                            });
                      }
                      return Container();
                    }
                    return Container();
                  })),
        ],
      ),
    );
  }
}

Individual page code

class Individual page extends StatefulWidget {
  static const String screen route = "Individual Page";
  const Individual page({super. Key});

  @override
  State<Individual page> create State() => _IndividualpageState();
}

class _IndividualpageState extends State<Individual page> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        background Color: Colors.blue,
        leading: Circle Avatar(
          child: Text("A"),
        ),
        title: Text('${Contact(display Name: )}'),
      ),
    );
  }
}
    Contact Fetch page contain permission handler and load contacts 
    show display name and phones Individual page code for each person 

Can I get the current url of an iframe if CORS between my website and the third party site is enabled? If so, how? [duplicate]

I’m working on a website that acts as a hub for multiple website and has a navigation bar on the side with links to each that will get rendered in an iframe when clicked. I’m trying to make it so you can leave one of those tabs and then when you go back, it will pick up from where you left off.

When I try to get the current url using iframe.contentWindow.location.href, I obviously get same-origin policy errors. I know you can use window.postMessage() to at least allow communication between the window and iframe but that still doesn’t make iframe.contentWindow.location.href work. If I enable CORS with my website inside of the 3rd party sites with http headers, how should I get the current url of the iframe?

The servers of the 3rd party sites are linux servers and my website is made with React + Vite. Not looking for a full solution to my code, just pointers to help me get going in the right direction.

Upload request to GCS via signed url fails apparently due to header mismatch due to apparent case sensitivity

I am trying to use a signed url to upload a file to my Google Cloud Storage. The code to create the signed url is this:

    // args have name of file and type
    // config has information about the bucket, etc
    const uploadOptions = {
        destination: args.name,
    };
    console.log(`Content-Type: ${args.fileType}`)
    const signingOptions = {
        version: "v4",
        action: "write",
        expires: Date.now() + 15*60*1000,
        contentType: args.fileType,
    };

    const response = Promise.await(myStorage.bucket(config.bucketName).file(args.name, uploadOptions).getSignedUrl(signingOptions));
    return response;

I then use this url to try to upload the file with fetch thus:

                // writeUrl is the url created by the above code
                fetch(writeUrl, 
                    {method: "PUT", 
                    origin: "https:localhost:3000",
                    headers: {"content-type": fileElement.files[0].type},
                    body: fileElement.files[0]})
                .then((response) => {
                    // Do something 
                })
                .catch((error) => {
                    console.log(error);
                })

This fails. The url returns an error message from the server that looks like this:

<Error>
  <Code>MalformedSecurityHeader</Code>
  <Message>Invalid argument.</Message>
  <Details>Your request has a malformed header. Header was included in signedheaders, 
    but not in the request.</Details>
  <ParameterName>content-type</ParameterName>
</Error>

This appears to be telling me I did not include a header “content-type”. But I did, see above. Looking at the network tab in Chrome, I see that the header is “Content-Type”. I am suspicious that case-sensitivity has showed up here. Am I correct about this?

One complication is that Chrome’s network says its description of the request headers is “provisional” I have caching turned off, which is one reason for this. The other reason is “the url is invalid”. Maybe because it returned an error?

I am vexed that I cannot find a way to keep fetch from changing “content-type” to “Content-Type”. Is there a workaround for this?

What is, in fact, wrong here? How can I get it to work?

Rendering Image from HTML in jsPDF

I have the given html

<html>
<img src="data:image/jpeg;base64,{base 64 of an image}" />
</html>

and I’m using the jspdf as follows where contents is the html from above as a string

const doc = new jsPDF({ format: "letter", unit: "px", hotfixes: ["px_scaling"] });
await doc.html(contents, { margin: inchesToPx(1) });
doc.save();

However, when I open the generated pdf in acrobat I get an error saying “insufficient data for image” or “There was an error while reading a stream”.

I can do everything else in html, but when it comes to images for jsPDF.html(), I can get it working with jsPDF.addImage(), but I need to do this with jsPDF.html()

Why My login status not updated immediately after redirecting to homepage in react?

I am getting an issues whenever i am logging in when it redirect to homepage my login status does not update instantly i have to refresh my page to get my login status updated and again refresh to get logged in user releated data why?

This is my front end login page

/* eslint-disable react/no-unescaped-entities */
/* eslint-disable no-unused-vars */
import axios from "axios";
import React, { useState } from "react";
import { Link, useNavigate } from "react-router-dom";
import { toast } from "react-toastify";

const Login = () => {
  const [email, setEmail] = useState();
  const [password, setPassword] = useState();
  const navigate = useNavigate();

  const handleSubmit = async () => {
    try {
      const config = {
        headers: {
          "Content-type": "application/json",
        },
      };

      const result = await axios.post(
        "http://localhost:5700/api/auth/login",
        { email, password },
        config
      );

      localStorage.setItem("userInfo", JSON.stringify(result.data));
      navigate("/");
      toast.success("User Logged In Successfully");
    } catch (error) {
      console.log(error);
    }
  };

  return (
    <div className="auth-container">
      <div className="auth-form">
        <header>Sign In</header>
        <div className="input">
          <label>Email</label>
          <input
            type="email"
            placeholder="Enter Your Email"
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            required
          />
        </div>
        <div className="input">
          <label>Password</label>
          <input
            type="password"
            placeholder="Enter Your Password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
            required
          />
        </div>
        <div className="auth-form-btn">
          <button className="auth-btn" onClick={handleSubmit}>
            Sign In
          </button>
        </div>
        <div className="login">
          Don't have an account? <Link to="/signup">Sign Up</Link>
        </div>
      </div>
    </div>
  );
};

export default Login;

This is my backend login logic

const login = async (req, res) => {
  try {
    const { email, password } = req.body;
    const user = await User.findOne({ email });
    if (user) {
      const validPassword = await bcrypt.compare(password, user.password);
      if (!validPassword) {
        res.status(401).send("Password is wrong");
      }
      res.status(200).json({
        name: user.name,
        email: user.email,
        token: generateToken(user._id),
      });
    } else {
      res.status(401).send("Invalid email");
    }
  } catch (error) {
    console.log(error);
  }
};

And this is my authorization logic

const jwt = require("jsonwebtoken");

const protect = (req, res, next) => {
  let token = req.headers.authorization;
  if (!token) {
    res.status(401).send("Access denied");
  }

  try {
    token = token.split(" ")[1];

    let verifiedUser = jwt.verify(token, process.env.TOKEN_SECRET);
    if (!verifiedUser) return res.status(201).send("Unauthorized Access");

    req.user = verifiedUser;
    next();
  } catch (error) {
    console.log(error);
    res.status(400).send("Invalid Token");
  }
};

module.exports = protect;

And this is my home page where i am redirecting after login

    /* eslint-disable no-unused-vars */
import React, { useEffect, useState } from "react";
import { UrlState } from "../context/UrlProvider";
import axios from "axios";
import { useNavigate } from "react-router-dom";
import { baseurl } from "../constants/constants";
import { toast } from "react-toastify";

const HomePage = () => {
  const [url, setUrl] = useState();
  const [urlData, setUrlData] = useState([]);
  const { user } = UrlState();
  const navigate = useNavigate();

  const [copied, setCopied] = useState(false);

  const handleSubmit = async () => {
    try {
      const token = user.token;
      const config = {
        headers: {
          "Content-type": "application/json",
          Authorization: `Bearer ${token}`,
        },
      };

      const result = await axios.post(
        "http://localhost:5700/api/urlShortner/",
        { url },
        config
      );
      fetchURL();
      toast.success("URL Generated Successfully!");
    } catch (error) {
      console.log(error);
    }
  };

  const fetchURL = async () => {
    try {
      const token = user?.token;
      if (user) {
        const result = await axios.get(
          "http://localhost:5700/api/urlShortner/",
          {
            headers: {
              Authorization: `Bearer ${token}`,
            },
          }
        );
        setUrlData(result.data);
      }
    } catch (error) {
      console.log(error);
    }
  };

  const copyLinkToClipboard = async (link, index) => {
    try {
      await navigator.clipboard.writeText(link);
      const updatedUrlData = [...urlData];
      updatedUrlData[index].copied = true;
      setUrlData(updatedUrlData);
      setTimeout(() => {
        updatedUrlData[index].copied = false;
        setUrlData(updatedUrlData);
      }, 1000);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    fetchURL();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  return (
    <div className="home-page">
      <div className="hero-section">
        <h1>
          Empower Your Links, Unleash Your Impact –{" "}
          <span style={{ color: "tomato" }}>BoniUrl</span>,<br></br> Where Every
          Link Tells a Heroic Tale
        </h1>
        <p>
          Create short links, Link-in-bio pages. Share them anywhere.<br></br>{" "}
          Track what’s working, and what’s not.{" "}
        </p>
      </div>
      <div className="container">
        <div className="form-container">
          <div className="form">
            <h1>Shorten a long URL</h1>
            <div className="input-group">
              <div className="input-label">
                {" "}
                <label>Paste a long URL</label>
              </div>
              <div className="input-box">
                <input
                  type="text"
                  placeholder="Example: https://super-long-link.com/jibrish"
                  value={url}
                  onChange={(e) => setUrl(e.target.value)}
                />
              </div>
              <div className="input-btn">
                <button className="btn" onClick={handleSubmit}>
                  {user ? "Get Your URL" : "Sign Up and get your URL"}
                </button>
              </div>
            </div>
          </div>
          <div className="view-url">
            <table className="link-table">
              <thead>
                <tr>
                  <th>Serial No</th>
                  <th>URL</th>
                  <th>Copy</th>
                </tr>
              </thead>
              <tbody>
                {urlData.map((link, index) => (
                  <tr key={index}>
                    <td>{index + 1}</td>
                    <td>
                      {baseurl}
                      {link.shortId}
                    </td>
                    <td>
                      <button
                        className="copy-btn"
                        onClick={() =>
                          copyLinkToClipboard(baseurl + link.shortId, index)
                        }
                      >
                        {link.copied === true ? "Copied" : "Copy"}
                      </button>
                    </td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
      </div>
    </div>
  );
};

export default HomePage;

How to update a chart with data coming from an API endpoint in Svelte?

I am using the Svelte JS web framework with the Chart.js charting library to plot a bar chart. I have created a Skeleton project and installed the svelte-chartjs and the chart.js packages:

npm install svelte-chartjs chart.js

Under the routes folder, I made the generate/+server.js endpoint to simulate the API calls:

import { json } from '@sveltejs/kit';

function getRandomNumber(min, max) {
  return Math.floor(Math.random() * (max - min) + min);
}

export function GET() {
  let randomNumbers = Array.from({ length: 12 }, () => getRandomNumber(10, 20));

  return json(randomNumbers);
}

It generates 12 random integer numbers between 10 and 20. Now, I can call this endpoint using the fetch('/generate') function on the root page. The content of the routes/+page.svelte file is the following:

<script>
  import { Bar } from 'svelte-chartjs';
  import { Chart, Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale } from 'chart.js';

  Chart.register(Title, Tooltip, Legend, BarElement, CategoryScale, LinearScale);

  let fetchedData = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12];

  let data = {
    labels: [
      'January',
      'February',
      'March',
      'April',
      'May',
      'June',
      'July',
      'August',
      'September',
      'October',
      'November',
      'December'
    ],
    datasets: [
      {
        label: 'Random Number',
        data: fetchedData,
        backgroundColor: 'rgba(98,  182, 239,0.4)',
        borderColor: 'rgba(98,  182, 239, 1)',
        borderWidth: 2
      }
    ]
  };

  let options = {
    responsive: true,
    maintainAspectRatio: false
  };

  async function generate() {
    const response = await fetch('/generate');
    fetchedData = await response.json();
  }
</script>

<h1>Fetch Data from API endpoint</h1>

<button on:click={generate}>Request</button>

<p>Current data: {fetchedData}</p>

<div>
  <Bar {data} {options} />
</div>

I have initialized the data with 1 to 12 integers, which is changed when clicking the Request button. Therefore, the data fetching is successful however the bar chart is not updated with the newly generated values.

k6 POST request receiving 401 unauthorized response when calling end point via Swagger

The application itself is similar to Facebook where the user needs to log in and can access different features of the app, such as Marketplace. I’m trying to run API performance tests on the application on a specific feature which calls a POST request. The POST request can be found via Swagger, and I’m using I’m trying test run k6 performance metrics on that POST request, however I’m getting a 401 unauthorized error. Here’s my code:

import http from 'k6/http';
import { check } from 'k6';

export default async function getTransactions() {
    const res = http.get('https://xxxxxx.net/xxxxx/xxxxxx/xxxx/xxxx/action?email=xxxxx&password=xxxxxx');
    check(res, { 'status was 200': (r) => r.status == 200 });

    const url = 'https://xxxxxx/api/jr/txn/session/v1'
    const payload = JSON.stringify({
        "atmId": [
            4
        ],
        "devtime0": 20231101000000,
        "devtime1": 20231111000000
  
    });
    const params = {
        headers: {
            'accept': '*/*',
            'access-control-allow-origin': '*',
            'content-type': 'application/json' ,
            'server': 'nginx/1.25.3',
        },
    };

    const transactionRes = http.post(url, payload, params)
    console.log(transactionRes.body);
    check(transactionRes, {'single transaction endpoint reached': (r) => r.status == 200});

}

I’ve tried getting authorization first with the GET call to the login page with the email and password needed to log in. I was hoping the cookies received back from that session would give me authorization to test an API endpoint with a POST call. I’ve been met with a 401 error instead however. My next suspicion is that I need an API key or token to proceed further. Would much appreciate guidance on how to proceed further with this!

Cannot access array elements in javascript, list[index] takes time to return

I need to go through an nested array of objects in javascript, at a particular index in a parent list.

My Code

  useEffect(() => {
    console.log(ssUpdater);
    if(ssUpdater === undefined)return;
    console.log(ssUpdater.length);//Can see this in console
    console.log(ssUpdater[ssUpdater.length-1]);//Can see this in console
    let temp= ssUpdater[ssUpdater.length-1]; //This is not an async function (How do I await here ???)
    console.log(temp);//Can see the full list in console (but with 'i' -this value was evaluated on first expanding ...)
    console.log(temp[0]); //Comes up undefined ?
    console.log(temp.length); //Shows as 0 ?
  }, [ssUpdater]);

In Console.log it shows the list items
As seen here, objects have correctly Showing.

But I can’t retrieve them using index.

Reading similar questions like this I think this might be because when console.log(scores[0]); is called, the array is still empty. It has not been populated yet. All the answers indicates one of two solutions

  • Either people have async / promise functions
  • They suggest JSON.stringify(obj) way but in my case that will just return an empty array

So whats the solution

Tried following solutions
Cannot access array elements in javascript

Can’t access object property, even though it shows up in a console log

With no luck

Replace HTML in string with placeholder, then put back after altering in javascript

Going from php functions I created long ago into JavaScript I am running into some roadblocks. A function that I have for altering content There are many steps I used regex to do but having a hard time translating to JavaScript.

I currently search for all and tags, replace them with an array index, store the content in that array, then later do a simple replace to return back, I am having a hard time creating the first part.

simple example would be

var string :string = "This is a sample with <b>bold</b> and a <a href=''>Link</a>";
var output = replaceHtml(string); //alter string without breaking HTML 
//  DO STUFF TO STRING
var completed = revertHtml(output);
// completed should have HTML added back in place
function replaceHtml(string){
    var store = [];
    // repolace <b>bold</b> with REPID0
    // replace <a href=''>Link</a> with REPID1
    return {store, string};
}
function revertHtml(output) {
    var ret = '';
    if (output.store[0] && output.string){
        output.store.map((d,i) => {
            ret = output.string.replace("REPID" + i, d )
        })
    }
    return ret;
}

Thanks!

Material UI – React: How to add breakpoints in CustomTheme for typography

I am using material ui and React to create SPA.

I am facing one issue where I want to make my pages response for smaller screen size. So I have to add fontSize: { xs: '30px', md: '56px' } in every text. I want to know if there is a way to do the same thing in my custom theme.

theme.js file

const theme = createTheme({
    palette: {
        mode: 'light',
        primary: {
            main: '#3f51b5',
            button: {
                bgColor: colors.buttonBgColor,
                borderColor: colors.buttonBgColor,
                hoverColor: colors.white
            },
            navBar: {
                topBarBgColor: colors.white
            }
        }
    },
    typography: {
        allVariants: { color: colors.black },
        fontFamily: roboto.style.fontFamily,
        hoverColor: colors.buttonBgColor,
        white: colors.white,
        h1: {
            fontSize: '56px',
            fontWeight: 600
        },
        h6: {
            fontSize: '17px',
            color: '#505556'
        },
        subtitle2: {
            fontSize: '17px',
            fontWeight: 400
        }
    }
});

export default theme;

I tried alot of thing from below but did not work.

breakpoint in material ui theme not changing font size for typography