How can I extract a substring from a URL and then save it to the clipboard?

Hi there! I'm working on a project for my school and could really use your expertise.

I need help extracting a substring from a URL, like this one: URL = https://www.example.com/blah/blah&code=12432 The substring is: 12432 I also want to display the substring in a Copy Box.

Your assistance with this matter would be greatly appreciated. It's crucial for my project to be able to extract text from a string.

(function() {
  var copyButton = document.querySelector('.copy button');
  var copyInput = document.querySelector('.copy input');
  copyButton.addEventListener('click', function(e) {
    e.preventDefault();
    var text = copyInput.select();
    document.execCommand('copy');
  });

  copyInput.addEventListener('click', function() {
    this.select();
  });
})();







   html, body {
          height: 100%;
        }
    
        body {
          font-size: 16px;
          background: #FFD1DD;
          display: flex;
          align-items: center;
          justify-content: center;
        }
    
        * {
          box-sizing: border-box;
        }
    
        .wrapper {
          padding: 0 5px;
        }
    
        h1 {
          text-align: center;
          font-size: 40px;
          margin-bottom: 1.2em;
          text-decoration: underline;
          text-transform: uppercase;
        }
    
        p {
          font-family: 'VT323', monospace;
          font-size: 20px;
        }
    
        .container {
          display: flex;
          background: #FFA3BB;
          border-radius: 7px;
          padding: 10px;
          margin: 0 auto;
        }
    
        h3 {
          font-size: 28px;
          text-transform: uppercase;
          text-align: center;
          
          span {
            display: inline-block;
            position: relative;
          }
        }
    
        .copy, .paste {
          flex-grow: 1;
          width: 50%;
        }
    
        .copy {
          border-right: 2px solid;
          padding-right: 10px;
          
          h3 {
            span {
              background: #76ECFF;
            }
          }
          
          input {
            padding-right: 90px;
          }
        }
    
        .paste {
          padding-left: 10px;
          
          h3 {
            span {
              background: #FAE916;
            }
          }
        }
    
        form {
          position: relative;
          width: 100%;
          
          input {
            display: block;  
            width: 100%;
            border: 3px solid;
            outline: 0;
            background: #FFF;
            font-size: 25px;
            padding: 5px 4px;
            margin-bottom: 20px;
          }
          
          button {
            display: block;
            position: absolute;
            top: 50%;
            right: 10px;
            transform: translateY(-50%);
            border: 0;
            outline: 0;
            color: #FFF;
            background: #000;
            font-family: 'VT323', monospace;
            font-size: 25px;
            text-transform: uppercase;
            padding: 0.08em 0.8em;
            cursor: pointer;
          }
        }

<div class="wrapper">
  <h1>Link Copy</h1>
  
  <p>Select the link text by clicking within the input then copy yourself or just click the copy button.  Paste into the paste side to see that it works!</p>
  <div class="container">
    <div class="copy">
       <h3>Copy <span><i class="fa fa-hand-peace-o"></i></span></h3>
      <form>
        <input type="text" value="https://codepen.io/she_codes/pen/OgrJJe/">
        <button type="button">Copy</button>
      </form>
    </div>
    <div class="paste">
      <h3>Paste <span><i class="fa fa-smile-o"></i></span></h3>
      <form>
        <input type="text">
      </form>
    </div>
  </div><!-- end .container -->
</div><!-- end .wrapper -->

Answer №1

Give this a try, it should do the trick

const query = new Proxy(new URLSearchParams(window.location.search), {
      get: (searchParams, prop) => searchParams.get(prop),
    });
    // Retrieve the value of "some_key" in for example "https://example.com/?some_key=some_value"
    let result = query.some_key; // "some_value"

Answer №2

Here's a simple method to extract the code parameter from a URL:

const getParameter = param => {
  const urlParams = new URLSearchParams(window.location.search);
  return urlParams.get(param);
}

const codeValue = getParameter('code');
copyInput.setAttribute('value', codeValue);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to verify if JSON.parse fails or yields a falsy outcome

Objective: const jsonData = JSON.parse(this.description) ? JSON.parse(this.description) : null When executing the above statement, my aim is to have the ability to parse a value successfully and return null if parsing fails. However, instead of achieving ...

What is the best way to ensure a NavBar stays at the top of the page when it is not collapsed?

I have integrated a NavBar using Bootstrap 5, which functions flawlessly. However, I am facing a specific issue that I haven't been able to resolve yet: When a user increases their screen size to <300%, it triggers the collapse button to appear. I ...

Move the object by clicking on it and dragging

I need help figuring out how to move my 3D object in .gltf format to a different position when a checkbox is checked, and then back to its original position when the checkbox is unchecked. I attempted to create a transition function for this purpose, but t ...

Trying to display logo using 'content' property in CSS

I've been trying to display a logo on the header of my website, but I'm having trouble getting it to show up. I attempted to set the logo using HTML syntax as well as the following CSS code: .div { content: url (...jpg); } However, both metho ...

Error Encountered in MERN Stack Development: TypeError Thrown Due to Inability to Convert Undefined

Currently, I am following the MERN Stack, Front To Back Course by Traversy Media. I am in the process of setting up the login functionality for the application. Despite ensuring that my code matches his exactly, I am encountering an error: TypeError: Canno ...

How can we effectively create reusable modals in React with the most efficient approach?

Currently, I am developing an application using React and Material UI. In order to streamline the use of Modals across multiple pages, I have implemented a global modal context that dynamically populates the modal with different props based on state change ...

What strategies can be utilized to condense code when needing to adjust a className based on various props?

I am looking to condense this code, particularly the [if~else if] block, in order to dynamically change a className based on different props passed. export default function Button(props) { const { name, height, color, bgColor } = props; let className = ...

Can HTML Elements be used within a Contenteditable section?

I am facing an issue with a contenteditable tag on my website. Users are unable to type code into the tag and have it display as an actual element instead of just text. Is there a way for users to input full, working HTML elements in a contenteditable box ...

Setting the Disabled and Checked attributes on HTML Elements based on certain conditions

Within an asp GridView template field, there is a button and a checkbox. The goal is to set the disabled property of the button and the checked property of the checkbox based on the Data Field Expiration conditionally. If the Expiration equals Permanent, t ...

Using a function parameter to restore the values of an array

Looking to clear an array using a function parameter. Below is my implementation: <script> fruitArray = ["apple", "banana", "orange", "pineapple"] function clearFruitArray(myArr){ myArr = []; ...

Invoke the parent's function within the Local-Registration component of VueJs

I have a Vue object: var app = new Vue({ el: '#my-id', data() { return { example: 1 } }, methods: { exampleMethos(data) { console.log('data', data); } }, ...

Encountering difficulties in creating an app with Apache Cordova

After setting up the proxy settings, I attempted to create a new app named "hello" using Cordova with the following commands: npm config set proxy http://proxy.company.com:8080 npm config set https-proxy http://proxy.company.com:8080 The creation comman ...

Extend and retract within a row of a table

I need help with modifying a dynamically generated table to meet specific requirements. The table currently looks like this. The task involves hiding all columns related to Category B, eliminating duplicate rows for Category A, and displaying entries from ...

Guide for transferring information from JavaScript to PHP on the same page

My dilemma lies in transferring data from my JavaScript script to PHP code for use within a query. Despite numerous attempts, I have been unsuccessful in achieving this. Below is my script for uploading files using an input type: file, where the URL is sto ...

Learn the simple steps to duplicate events using ctrl, drag, and drop feature in FullCalendar v5 with just pure JavaScript

My goal is to incorporate CTRL + Drag & Drop functionality in FullCalendar v5 using nothing but pure JavaScript. I delved into the topic and discovered that this feature has been discussed as a new UI feature request on the FC GitHub repository. There ...

Issue with updating bound property correctly when dynamically generating components using v-for in Vue.js

Encountered a challenge with vue.js and seeking guidance on the best approach to address it. Here's a concise summary of the issue: Situation Data is fetched from a rest API, handled by a class called DataLoader using javascript prototype syntax. Th ...

A guide on how to activate an event when a radio button is selected using jQuery

I experimented with implementing this. When I try clicking on the radio button, the code functions correctly, but the radio button does not appear to be checked and remains unchanged. Any ideas on how to resolve this issue? <p> <input id="p ...

What is the best approach to managing categorical variables with Flask?

After developing a machine learning model to classify a target variable Y based on predictors x1, x2, x3, and others, I needed to create an HTML form "calculator" for users. The form requires the user to input data for x1, x2, x3, etc., and then displays t ...

Multi-Slide AngularJS Carousel

My current setup includes a carousel like so: <div> <carousel id="myC" interval="3000" > <slide ng-repeat="order in orders"> <img ng-src="whatever.jpg" style="margin:auto;"> <div ...

Having trouble connecting local stylesheet on server?

Currently, I am developing an HTML-based game with Node.js, focusing on enhancing the front-end interface. While trying to include a CSS stylesheet, I encountered an unusual issue. The structure of my folders is organized as follows: C:\Users\m ...