Find and replace string words containing special characters such as $ or !

Looking to process an input string in a specific way -

// Input string - 
'My pen cost is !!penCost!! manufactured in $$penYear$$ with colors !!penColor1!! and $$penColor1$$'
// Processed string
'My pen cost is <penCost> manufactured in <penYear> with colors <penColor1> and <penColor1>'

While I have achieved this using a loop, I am curious about a RegEx approach. Here is my current attempt (not functioning as expected) -

const regex = /\b(\w*([a-zA-Z])|([\!]{2}[a-zA-Z][\!]{2})\w*)\b/g;
// The 'str' variable holds the input string
str.replace(regex, (match) => {
  return `<${match.substring(2, match.length - 2)}>`;
});

I'm struggling with the RegEx to correctly identify words with values like "$$[a-zA-Z0-9]$$" or "!![a-zA-Z0-9]!!".

My methodology combines word matching and match replacement.

Answer №1

Feel free to utilize the following code snippet:

str = str.replace(/(!!|\$\$)([\w-]+)\1/g, '<$2>');

Check out a demo of this Regular Expression in action here

Here are the details of the RegEx pattern used:

  • (!!|\$\$) Match either !! or $$ and capture it within group #1
  • ([\w-]+) Match one or more word characters or hyphens and catch it in group #2
  • \1: Ensure that the string ends with the same delimiter as captured in group #1
  • The replacement text is <$2>, which wraps the matched string from group #2 inside < and >

Example Usage:

const str = 'My pen cost is !!penCost!! manufactured in $$penYear$$ with colors !!penColor1!! and $$penColor1$$';

const res = str.replace(/(!!|\$\$)([\w-]+)\1/g, '<$2>');

console.log(res);
//=> My pen cost is <penCost> manufactured in <penYear> with colors <penColor1> and <penColor1>

Answer №2

programming

[!,$]{2}[A-Za-z0-9]+[!,$]{2}

Answer №3

Give this a shot:

// Input string - 
const str = 'My pen cost is !!penCost!! manufactured in $$penYear$$ with colors !!penColor1!! and $$penColor1$$'
const result = str.replace(/[!$]{2}(\S+)[!$]{2}/g,"<$1>")
console.log(result)

// Processed result
// My pen cost is <penCost> manufactured in <penYear> with colors <penColor1> and <penColor1>

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

Capture data from Ajax requests and store them in PHP variables

When setting up a DDBB Insert using $.ajax, I encountered an issue. $(document).on('click','.submitMessage', function(){ content=$('textarea').val(); img=$('#messageImg').val(); stdMsg=$('.ms_stdMsg ...

HTML5 input placeholder adapts its size and position dynamically as data is being

During my interaction with the input fields on my bank's website, I noticed that the placeholder text undergoes a unique transformation. It shrinks in size and moves to the upper-left corner of the input field while I am entering information. Unlike t ...

Transitioning to Vue 3: [Vue warning]: Prop already has a computed property named "actions"

Currently in the process of migrating a Vue 2 application to Vue 3, I've encountered an issue where I am frequently seeing this warning: [Vue warn]: Computed property "actions" is already defined in Props. This warning pops up in various c ...

Switch the website title as soon as the user looks away from the tab

How can I capture the user's attention and bring them back to my website when they are on a different tab? I really like the effect used on sephora.pl where an alert pops up with the message 'What are you waiting for?' when you switch tabs. ...

In React, is it typical to maintain identical values in both state and ref?

When working with my React app, I encountered a situation where I needed to access state values inside setTimeout() and setInterval(). However, due to closures being bound to their context once created, using state values in these functions would not refle ...

Display multiple markers on a Google Map using google-map-react library

I am currently struggling to display markers on my Google Map using the map function. I have tried various approaches but nothing seems to work. Could there be limitations that I'm not aware of, or am I overlooking something critical? I experimented w ...

javascript utilizing key inputs

Is there a way I can create a function that activates when the "A" key on my keyboard is pressed, sending a signal to nupp('/TS'), and stops sending the signal when the "A" key is released? <html> <head> <script src=\"htt ...

Encountering an issue with the message: "Property 'ref' is not available on the type 'IntrinsicAttributes'."

Having trouble implementing a link in React and TypeScript that scrolls to the correct component after clicking? I'm using the useRef Hook, but encountering an error: Type '{ ref: MutableRefObject<HTMLDivElement | null>; }' is not assi ...

NodeJS Error: Attempting to access 'json' property from an undefined source

I'm in the process of setting up a CronJob to make an API call and save the response into the database: const CronJob = require("cron").CronJob; const btc_price_ticker = require("../../controllers/BtcExchange/Ticker"); const currency = require("../.. ...

Error: Firebase has encountered a network AuthError, which could be due to a timeout, interrupted connection, or an unreachable host. Please try again later. (auth/network-request-failed

I have set up my Angular app to utilize Firebase's emulators by following the instructions provided in this helpful guide. In my app.module.ts, I made the necessary configurations as shown below: import { USE_EMULATOR as USE_AUTH_EMULATOR } from &apos ...

Storing an array within an AngularJS service for better performance

As someone who is relatively new to AngularJS, I am still in the process of understanding how to utilize services for fetching data in my application. My aim here is to find a method to store the output of a $http.get() call that returns a JSON array. In ...

Is it possible to implement pagination using 'useSWR' in combination with the contentful-client?

I am currently working on implementing pagination in a Next.js project using the useSWR hook. My approach seems to be functioning correctly, but I have a concern about caching due to the key parameter not being a unique string as recommended in the documen ...

How do I set up Firebase functions to trigger onWrite when listening for a specific child just once?

Is there a way to access the child under a different node each time the Firebase onWrite function is triggered? To retrieve this child, you can use the following code: {const saatt = (context.database.ref('kullanicilar/1111/marina1/2021/1saat'). ...

Custom sample rate options in RecordRTC allow for the recording of silent audio tracks

I am currently working on implementing RecordRTC.js to capture audio from a microphone and then upload it to a server built with nancyfx. Initially, I am simply aiming to upload the audio stream and store it in a wav file for testing purposes. However, my ...

Switching from HTML to BBCode during the editing process

My issue lies in converting BBCode to HTML and then editing the code on a page with AJAX. When editing in a <textarea>, the HTML tags show up instead of the original BBCode. For instance, if I submit [b]bold text[/b] and save it to my database, the ...

What are the appropriate scenarios to utilize the declare keyword in TypeScript?

What is the necessity of using declare in TypeScript for declaring variables and functions, and when is it not required? For instance, why use declare var foo: number; when let foo: number; seems to achieve the same result (declaring a variable named ...

The "maxfilesexceeded" event in dropzone.js does not seem to be triggered when adding files programmatically

In my Vue.js project, I am using dropzone with the maxFiles: 1 option set. To display an existing file from the server in dropzone, I have added the following code: let mockFile = { name: 'Filename', size: file.size }; myDropzone.emit('added ...

Ways to verify the input fields across multiple tabs

Utilizing jquery validate along with jquery tabs to construct a multi-tab form. Consider a basic form : tab 1 for entering address, tab 2 for entering name, tab 3 for submission HTML <ul class="nav nav-tabs"> <li class="active"><a hr ...

Encountering a SyntaxError while implementing lightweight-charts in NextJS

I'm encountering an issue while trying to integrate the lightweight-charts package into my nextjs project. When attempting to utilize the createChart function, I am receiving a syntax error in my Node.js console. ...\lightweight-charts\dist& ...

Retrieve the total number of clicks and initiate a single AJAX request using jQuery

When a user continuously clicks a link, I need to call an ajax service. Currently, my code only works for a single click - the ajax call is made and functions correctly, but if the user clicks multiple times, only the first click is registered. I want to k ...