Using Regular Expression in JavaScript to replace variables within a string

Looking for assistance to replace keywords in a string with pre-defined variables. Currently, the code only displays variable names instead of their content. Can anyone provide help?

Desired Output:

1111Test1
2222Test2
3333Test3

Current Output:

1111aa
2222bb
3333cc

Code snippet:

var aa = "Test1";
var bb = "Test2";
var cc = "Test3";
var str_before = "1111{t:aa}\n2222{t:bb}\n3333{t:cc}";
var str_after = str_before.replace(/\{t:\s*(\w+)\}/g, "$1");
alert(str_before+"\n\n"+str_after);

Answer №1

You can't directly reference a variable in a regular expression constant (i.e. /.../ syntax).

One workaround is to utilize the callback parameter of the .replace function:

var map = {
    aa: 'Test1',
    bb: 'Test2',
    cc: 'Test3'
};

var str_before = "1111{t:aa}\n2222{t:bb}\n3333{t:cc}";
var str_after = str_before.replace(/{t:(\w+)}/g, function(match, p1) {
    return map.hasOwnProperty(p1) ? map[p1] : '';
});

This approach also allows for easy configuration of your mapping from name to value, eliminating the need for separate variable declarations.

Answer №2

If you're in need of a solution for replacing variables within a string, look no further than this handy NPM package. Simply provide the string and an array of variables to replace them with. Check out a basic example and access to the package via the links below:

Example:

var str = "This is a {0} string for {1}"
var newStr = stringInject(str, ["test", "stringInject"]);

// This is a test string for stringInject 

NPM / GitHub links:

https://www.npmjs.com/package/stringinject

https://github.com/tjcafferkey/stringinject

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 conceal the header on a 404 error page?

<HeaderContainer> <Switch> <Route exact path='/counters' component={ParentCounterContainer}/> <Route exact path='/about' component={AboutContainer} /> <Route exact path='/' component={H ...

How to retrieve data obtained from parsing readline and fs in node.js beyond the scope of the callback function

This specific question diverges from the one mentioned with an existing answer. It pertains to a snippet of code taken from node.js documentation involving the use of fs and readfile, with a focus on detecting an end-of-file flag, which appears to be the r ...

Create a customized MUI select component with a label, all without the need for assigning an

One issue I am facing is with the Material UI React select component being used multiple times on a page. In the examples, all labeled selects use InputLabel with htmlFor that must match the id of the select. The challenge is that I cannot assign an id t ...

Modifying SASS variable values based on the presence of specific text in the page URL

How can I utilize the same SASS file for two different websites with similar functionality but different color schemes? My goal is to dynamically change the color based on the URL of the page. However, I am facing challenges in extracting the page URL from ...

Struggling with textpath SVG elements in jQuery

Currently, I am implementing SVG in my project and aiming to apply the toggleClass function using jQuery on the textpath elements upon clicking. My initial plan was: $("text#names > textpath").click(function() { $(this).toggleClass("newClass"); }) ...

Verification - enter a unique key for each ajax call

As I develop a new app, I am aiming to separate the HTML/JS layer from the PHP layer in order to prepare for a potential phonegap version in the future. One major concern I have is regarding authentication. Since I won't be able to rely on session va ...

Strange issue encountered when utilizing Worklight along with XSL transformation on a JSON response

I'm facing an unusual issue that I can't seem to resolve. Here is an example of a JSON response that I am dealing with. "values": [ { "time": "2014-02-26T09:01:00+01:00", "data": [ "A", "B" ] }, // additional objec ...

Incorporate HTML and JavaScript to dynamically show a button when a specified condition evaluates as true and hide the button if the

I need help with a scenario where I want to show a button only when a specific variable reaches a certain value. For instance, if the variable equals 5, the button should be displayed; otherwise, it should be hidden. Here are the two buttons included withi ...

JavaScript code to find a date within a specified range

I have developed a script that calculates the number of weeks between two specified dates. It then generates a table where the number of rows equals the number of weeks. The script can be viewed on JSFIDDLE Script: $('#test').click(function ...

Identifying whether a Alphabet or a Digit has been Pressed - JavaScript

I understand that it is possible to detect if a key has been pressed and identify which key was pressed using JavaScript. In order to check if a key is down or pressed, jQuery can be utilized with ease: $( "#some id" ).keydown(function() or $( "#m" ). ...

Group an object by its name using Java Script/Vue.Js

I am looking to group objects by partial name and assign them to variables data = { SCHOOL-ADMISSION_YEAR: "2021" SCHOOL-SCHOOL_NAME: "ABC SCHOOL" SCHOOL-SCHOOL_LOCATION: "NEWYORK" ENROLLMENT-ADMISSION_YEAR: " ...

Evaluating QUnit Test Cases

How do you write a test method in QUnit for validating functions developed for a form? For example, let's consider a form where the name field should not be left blank. If the validation function looks like this: function validNameCheck(form) { if ...

tips for showcasing an item in a tooltip within a data table

I am working on dynamically creating a table with data retrieved from an ajax response. My goal is to display the data stored in an object within a tooltip attached to each cell. Currently, I have successfully rendered the table, but it is displaying `[obj ...

The value of the comment box with the ID $(CommentBoxId) is not being captured

When a user enters data in the comment box and clicks the corresponding submit button, I am successfully passing id, CompanyId, WorkId, and CommentBoxId to the code behind to update the record. However, I am encountering an issue as I also want to pass the ...

Updating a ReactJS component based on the selected value

My code currently includes a select element that retrieves ID's from an API, followed by a table that displays data. When I define a state like this example: this.state = {value:23}; the table successfully displays data from I'm trying to achie ...

Managing HTML5 Video in a slider

I've designed a unique video slider that cycles through 4 videos. Each video has a custom play button and additional overlay content. Once the video starts playing, the overlay content and play button fade out to reveal the default video controls. The ...

Surprising automatic scrolling upon pressing the keydown button in Bootstrap

My webpage appears normal with the Bootstrap framework, but whenever I press the down key, the screen scrolls down and displays unexpected white space due to reaching the end of the background-image sized at 1798px * 1080px. Please refer to the image: He ...

Tips and tricks for manipulating base64 images in Node.js

I have a unique challenge - I want to manipulate a base64 picture by adding just one extra pixel. My goal is to send a base64 image string (e.g. data:image/png;base64,iVBORw0KG...) from my express server. Let's say the image is 100x100px and I need to ...

Is it possible to simultaneously run multiple functions with event listeners on a canvas?

I'm attempting to create a canvas function that displays the real-time mouse cursor location within the canvas and, upon clicking, should draw a circle. I came across this code snippet that reveals the x and y coordinates of the mouse: document.addEve ...

The clearTimeout function in React stateless components does not appear to be functioning properly

I am facing an issue with a component that I developed. In this component, one value (inclVal) needs to be larger than another value (exclVal) if both are entered. To ensure that the function handling this comparison doesn't update immediately when pr ...