Duo and reference loop

I'm trying to learn how to use backreferences in JavaScript. I have an array and want to replace it within a string.

Here's what I've attempted so far:

var items = ["book", "table"];

var sentence = "The $1 is on the $2";

var newSentence = sentence.replace(items, "$2, $1");

console.log(newSentence);

Answer №1

It's quite perplexing to me how one could come up with such a confusing idea...

Here's an alternative solution:

newstr = str.replace(/\$(\d)+/g,function(_,id) {return cc[id-1];});

Answer №2

Give this a shot:

let items = ["pen","desk"];

let sentence = "The $1 is on the $2";

let newSentence = sentence.replace('$1', items[0]).replace('$2', items[1]);

alert(newSentence);

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

What is the best way to store multiple values in local storage using useState in react?

Currently, I am exploring how to utilize multiple values in the useState hook and perform CRUD operations in local storage. Here is an example of my code: const [Data,setData]=[[{ name:'luis', pass:'1234', //....... }]] // ...... ...

Why does my Redux callback keep getting invoked multiple times?

In developing a react application with redux, I have chosen to avoid using react-redux by manually handling all dispatched events. Below is a sample code snippet. The content of index.html <!DOCTYPE html> <html> <head> <script src=& ...

Laravel validation successfully validates Vanilla AJAX request, but the controller does not receive the values

Currently, I am utilizing AJAX (vanilla JS) to send a form to a Laravel 5.5 controller for searching the Amazon products API. The AJAX is sending the correct keywords and category inputs, but the controller is not receiving them. Even though the request p ...

After mapping the elements of the array twice, generate a new array

Two differently formatted bits of data may be received, each requiring different character stripping methods. The variable names are temporary and will be changed once the function is operational. const cut = flatten.map(obj => { return obj.file. ...

Utilizing grease/tampermonkey (or any other browser extension) to filter out specific characters within webpage elements

Forgive me if my language is not accurate, as I am still learning about programming. The forum that I visit has cluttered the page with unnecessary and glitchy images and text for a promotion. This has made the forum difficult to navigate. I was successful ...

The Angular UI Datepicker is not reflecting changes in scope variables within the dates-disabled function

I'm currently working with AngularJS and the Angular UI Bootstrap. I've encountered an issue that I initially thought was related to scope, then initialization, but now I'm stuck trying to figure out what's causing the problem. I' ...

Unable to send POST request (including data) using event trigger from an external component

I'm currently facing an issue where a click event in one component is triggering a method in another, but the data that should be passed in my POST request isn't being sent. Interestingly, when I test the functionality by calling the method dire ...

Ionic - numerical age selector control

Currently working on a hybrid mobile app and ran into a specific issue. I'm in the process of adding new items to my left side menu, including an age number spinner component (min:18, max:65). After searching through various sources and Ionic documen ...

Verify the entered information in the input field and showcase it in the display box after pressing the ENTER key

I need to display selected values of a tree structure in a show box on the other side of the page using code. However, I also need to include HTML input boxes in some lines of the tree structure so that users can input data. The challenge is getting the in ...

How to extract selected value from a dropdown menu in a React component

Is there a way for me to retrieve the chosen value from the dropdown menu? The select dropdown contains 12 options. My goal is to capture the selected value and then utilize it in handlecolumnchange to manipulate the number of columns added or removed. Des ...

Prevent the onclick function of a span element from being triggered when the user clicks on a dropdown menu contained within

Just delving into the world of web development and currently tackling a React project. Encountered an issue where I need to make a span element clickable. However, there's a dropdown within that span that doesn't have any onClick event attached t ...

Tips for incorporating a multiple tag search feature within my image collection using JavaScript?

I am facing a challenge with my image gallery search feature. Currently, users can search for images by typing in the title or tag of an image. However, I need to enhance this functionality to allow for multiple tags to be searched at once. For example, if ...

Displaying JSON data in a popup window resembling a download prompt

I'm a beginner in front end development and facing difficulty in displaying JSON in a new window. Currently, I'm allowing users to download the JSON file like this var blob = new Blob([$scope.data], {type: 'json'}); ...

In TypeScript, use a Record<string, any> to convert to {name: string}

I have developed a custom react hook to handle API calls: const useFetch: (string) => Record<string, any> | null = (path: string) => { const [data, setData] = useState<Record<string, any> | null>(null); var requestOptions: Requ ...

What is the best way to dynamically change the content of a div based on user selection?

When a user selects an option in the HTML, I want to display another div set to Block. I tried putting the OpenAskuser() function in a button, but it didn't work either. It would be ideal if we could achieve this without a button. Just have the displ ...

The setInterval timer is malfunctioning within the render() method of ReactJS

In my React component, I have a countdown timer that starts at 10 seconds. If the backend data is received within this time frame, the timer stops. If not, it will continue counting down to 0 and then refresh the page, repeating the cycle until the data is ...

Using Javascript and jQuery, populate a dropdown menu with options that are extracted from a different dropdown menu

These are my two <select> elements: <select class="js-select-1"> <option disabled>Starting point</option> <option>A</option> <option>B</option> <option>C</option> <option>D</op ...

Tips for organizing a search using two keys in Javascript

I am dealing with a large dataset containing over ten thousand objects that hold information about two different ids as shown below: dataSet = [ { ids: ["123", "234"], information: 1 }, { ids: ["123", "345"], in ...

Are you struggling with Grails - Ajax submission not functioning properly?

Trying to update a div when a form is submitted, but it seems like something is missing. Here's the HTML code: <%@ page contentType="text/html;charset=UTF-8" %> <html> <head> <meta name="layout" content="main" /> ...

Positioning html images to overlap each other without losing the ability to click

Currently, I am facing a challenge with positioning two images over each other. The back image should be at the bottom, while the center image needs to be on top of it. Additionally, there is a requirement for placing a random link (in this case google.com ...