JavaScript String Replacement (similar to Query Binding)

Thank you for taking the time to address my query. I believe that what I am looking for is not exactly string interpolation, so I have adjusted the title accordingly. Before dismissing this as a duplicate related to string interpolation in JavaScript, please carefully consider the specifics of my question. While I have explored other questions on interpolation in JavaScript, none of them provide the exact solution I am seeking for my code (I explain the reasons in my question), and I prefer not to rely on plugins.

Hello everyone, let me clarify the purpose behind this code. The main objective is to create Query Binding for Express with MySQL, but I intend to utilize this code for other purposes as well.

I am interested in achieving string interpolation in JavaScript/Typescript that functions similarly to Query Binding in Code Igniter - you can find an example here.

// Code 1
let person = 'ujang'
let age = 23

console.log("Hello, %s. You're age is %d years old.", person, age)
// Hello, ujang. You're age is 23 years old.

// A function similar to this code
// $sql = "insert into tbl_user (name, age, groupname) values (?, ?, ?)";
// $this->db->query($sql,array('codeigniter, 35, 'Group 1'));

In the above code snippet, I utilize console.log as it aligns with my requirements, however, since console.log returns void and does not return any value, it cannot be used in practical scenarios.

// Code 2
const str = 'hello, %s. Do you want %d slices of cake?'
const name = 'ujang'
const quantity = 13

const myFunction = (value, ...optionalParams) => {

    // The function I need should resemble Query Binding in Code Igniter
    // And accommodate dynamic parameters
    // This is just a sample
    value = value.replace('%s', optionalParams[0])
    value = value.replace('%d', optionalParams[1])
    return value
}

myFunction(str, name, quantity)
// hello, ujang. Do you want 13 slices of cake?

In Code 2, I attempted to create a function that operates as desired, albeit only for static parameters.

// Code 3
const names = 'ujang'
const arg1 = 'good' 
const argN = 'better'

const dontWantFunction = (value, arg1, argN) => {

    return `hello, ${value}, this function may be ${arg1} but there could be a ${argN} alternative.`
}

dontWantFunction(names, arg1, argN)
// hello, ujang, this function may be good but there could be a better alternative.

In Code 3, I crafted a function that does not meet my expectations as it is difficult to manage and contains hardcoded text within.

Could anyone assist with refining the myFunction in Code 2?

Is anyone else working on a similar codebase?

Alternatively, does anyone know of any documentation or articles that might guide me towards a solution?

Your insight and assistance would greatly benefit me. Thank you for your attention.

Answer №1

One approach you could take is to extract values from the optionalParams sequentially and use them to replace matching placeholders.

const str = 'helow, {{value}}. and you want {{value}} piece of cake.?'
const name = 'ujang'
const want = 13

const myFunction = (value, ...optionalParams) => {
  return value.replace(/\{\{value\}\}/g, (m) => optionalParams.shift() || m)
}

console.log(myFunction(str, name, want))

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

Sending a JSON data blob containing various values to an Ext JS panel

I am currently enhancing an element of my application dedicated to managing client information for a business. Initially, I only stored notes within the clients table along with other attributes. However, to improve functionality, I decided to create a sep ...

Why can't I use React.findDOMNode?

Currently, I am working on a React.js CRUD application and I have been using React.findDOMNode to create records. handleSubmit: function(e) { e.preventDefault(); name = React.findDOMNode(this.refs.name).value.trim(); email = React. ...

What is the process for performing type checking on an array variable designated as "as const"?

Check out this code snippet: export type Types = 'a' | 'b'; export type MyPartials = { readonly [P in keyof Types]?: number; }; export interface MyI { readonly name: string; readonly myPartials: MyPartials; } export const myI ...

Functionality Issue: Submit Button Not Working on Designed Form Select

Through dedication and hard work, I managed to create a customized form with images that display correctly in Firefox, Chrome, and Internet Explorer's compatibility mode. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w ...

Assigning string properties to different types

I have numerous data types, each with a common property called dataType, and I am currently mapping each one to that specific value: interface GroupData { dataType: "group"; name: string; people: PersonData[]; } interface PersonData ...

Create a function that adds a new div element with a one-of-a-kind identification when

I am currently developing a web application on www.firstusadata.com/cash_flow_test/. The functionality involves two buttons that add products and vendors dynamically. However, the issue I'm facing is that the appended divs do not have unique IDs, maki ...

Provide the identifier of the label within the JavaScript function that is being passed in the textbox event

I need to pass the client ID of a label as a parameter in a JavaScript function. The goal is to show or hide the label based on whether there is a value in a textbox or not. Here is the code snippet: <label> First Name:<asp:Label ID="lblfn ...

deactivate the struts anchor link once the request is sent to the action

To prevent users from clicking the anchor link multiple times while a request is being processed on the server side, I need to disable the anchor tag after sending the action and wait for the response. Additionally, there is an onclick event in my anchor t ...

The significance of the "? :" operator in JavaScript

These are the lines of code I am currently working with: toggleMore : function( $item, show ) { ( show ) ? $item.find('a.ca-more').show() : $item.find('a.ca-more').hide(); }, Could someone help me understand what this code does? ...

Retrieve data from the class or ID within an HTML document and display it on the webpage

Looking to transform a WordPress post into a custom layout by extracting only the title and content for use in an Android application The process involves entering the post's URL, retrieving just the title and content, then displaying it in a unique ...

Identifying a broken lock icon caused by a mix of secure and insecure content using JavaScript

Currently, I am in the process of ensuring that our website is fully functional under HTTPS. One important aspect of this is to prevent any occurrence of "breaking the lock." It is crucial not to load non-SSL content on an SSL page as this can result in a ...

Transform an array of objects into a single string and add it back into the original array

The format of my Array is as follows:- questionValue = { others: [{ inputValue: [{ FormTypeValueArrayValue: [ { form_type_value: "a" }, { form_type_value: "b" }, { form_ty ...

Assigning a specific data type to an object in TypeScript using a switch case statement

I am currently developing a React Native app using TypeScript. As part of my development, I am creating a handler with a switch case structure like the one below: export const handleMessageData = (dispatch: Dispatch, messageData: FCMMessage): void => ...

Highlight the parent item when the child item is being hovered over

I am working on a menu that has 2 submenus. I want to use jQuery to highlight the item when it is hovered over. However, I am struggling with how to also highlight the parent item when the cursor is on the child item. The class I am using for highlighting ...

Add a conditional class to a particular element in a Vue.js 3.0 list based on certain conditions

I'm trying to dynamically disable a specific link in a list generated by Vue.js. Here is my current implementation: <ul> <li class="nav-item" :key="id" v-for="(item, id) in listOfItems"> <a class=&quo ...

using vuejs, learn how to retrieve properties within the .then function

This is the code I am working on: methods: { async pay() { this.$notify(`working`); if (!this.$v.$invalid) { try { var data = { to: this.to, subject: this.subject, }; let resp ...

Compelling users to provide feedback on an App with the Ionic Framework

As a novice developer, I could use some assistance with implementing ratings in my app. My goal is to show menu items based on whether a user has given my app a 5-star rating. For instance, if a user gives a 5-star rating, I would assign the class "review ...

Best Practices for Storing User Data in Single Page Applications

While working on a Single Page Application (SPA) using AngularJS, I encountered an issue with storing user data in an Angular Value service. I realized that the data was not being shared between browser tabs, leading to constant requests to the server for ...

Issue with disappearing backdrop in Bootstrap 4 modal close operation

Using boostrap 4, I include the following css: <link rel="stylesheet" type="text/css" href="//stackpath.bootstrapcdn.com/bootstrap/4.1.0/css/bootstrap.min.css"> And this js: <script src="//stackpath.bootstrapcdn.com/bootstrap/4.1.0/js/bootstrap ...

Guide to crafting a reply using nestjs exception filters with nestfastify

I'm facing a challenge with writing custom HTTP responses from NestJS exception filters. Currently, I am using the Nest Fastify framework instead of Express. I have created custom exception filters to handle UserNotFoundException in the following mann ...