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

The Correct Way to Implement Return in jQuery Ajax

Encountering an issue with the login form where I am unable to proceed to the next page after entering my credentials. The system acknowledges if the email and password match, however, the login does not go through. Seeking assistance in identifying the ...

The concept of "HTML paragraph shifting"

I am looking to implement a feature similar to paragraph sliding, but I am struggling to explain it clearly. For demonstration purposes, I have added it to my website for you to view. Please note that it may take some time to load. The paragraphs slide s ...

Typescript's tree-pruning strategy design for optimization

I've been working on developing a library that enforces the use of specific strategies for each target. The current structure I have in place is as follows: [Application] -> contains -> [player] -> contains -> [renderer] In the current s ...

What is the method for viewing the content within div tags on an apex page?

Locationbox is a system outside of Salesforce, similar to Google Maps. An example can be viewed here; I am aiming to integrate it into the Salesforce platform. The first script tag fetches JavaScript code from the Locationbox service. Once the startup() f ...

Ensure history.back() does not trigger Confirm Form Resubmission

Within my web application, every form submission is directed to an action folder. Once the process is complete, the user is redirected back to their original location. However, a problem arises when the user performs an action that requires the application ...

Adjust the autofocus to activate once the select option has been chosen

Is there a way to automatically move the cursor after selecting an option from a form select? <select name="id" class="form-control"> <option>1</option> <option>2</option> <option>3</option&g ...

Trouble with hide/show loop in setTimeout function

I have a special animation with 3 text items that are initially invisible. The goal is to make these items appear one by one with a delay of 2 seconds after clicking a button. Each item should be visible for 1 second before fading out and making way for th ...

Display the duplicated values of an array extracted from a JSON object just once

Having some trouble creating a list from json data, you can check out the example. My goal is to display each value only once if duplicates occur (for example, if there are 2 Martini glasses, I only want one to appear in the list), while still preserving t ...

Populating a clickable list and form with a complex JavaScript object

I have a code snippet that takes an unstructured String and parses it into a JavaScript object. My next step is to integrate it into a web form. You can check out the demo here. The demo displays the structured object hierarchy and showcases an example of ...

How do I specify the default checked value for a checkbox in Redux Form?

Within our Redux Form 5.3 application (not version 6.x), the goal is to display an <input type="checkbox" /> in this manner: // Sometimes, fieldHelper.checked starts off as undefined. When a checkbox is // clicked by the user, fieldHelper.checked is ...

Is there a problem with evalJSON() causing Simple AJAX JS to work on Safari locally but fail on the server and in Firefox?

I created a script that utilized Prototype's AJAX methods to fetch Twitter data in JSON format, process it, and display it within a div. The script was functioning perfectly during testing on Safari 4.0.3 on an OS 10.6.1 machine. However, when I uploa ...

What is the best way to customize the style of a react.js component upon its creation?

Is there a way to set the style of a react.js component during its creation? Here is a snippet of my code (which I inherited and simplified for clarity) I want to be able to use my LogComponent to display different pages of a Log. However, in certain ins ...

Best method for simultaneously calling multiple routes in Node.js and Express

What is the best approach for handling multiple routes simultaneously in Node.js and Express? For instance, if I have two routes defined as app.get('/', routes.views.index); and app.all('/header', routes.views.header); I want both route ...

Exploring recommendations using AngularJS

I am currently working on replicating the search suggestion feature found at: where certain words are displayed as you type in the search box. Here is my HTML setup: <form ng-controller="SearchCtrl"> <input name="q" ng-model="query" ng-keyp ...

Modify the useRef value prior to the HTML rendering (React functional component)

Hello everyone, I am attempting to update the value of useRef before the HTML is rendered. I have tried using useEffect for this purpose, but it runs after the HTML is ready, making it unsuitable for my needs. What I want to achieve is resetting the value ...

Mixing up letters using a shuffle function

Seeking assistance as a newcomer here. I have a shuffle function triggered by pressing the reset button with class="reset" on the img tag. How can I make it load shuffled from the start? So that when loading this page, the letters do not appear in alphabet ...

Tips for concealing lengthy text within a select box and automatically wrapping it when displayed as an option

Is there a way to conceal lengthy text within a select box and display it only when the option is selected? I want to hide long text in a select box options, but have some sort of signal to show that more text is available. Is there a javascript solution ...

Has anybody managed to successfully implement this require or debug NPM module for use in a web browser?

Has anyone successfully implemented the require or debug NPM modules in a browser environment? Despite claims and instructions on the debug NPM module's page that it can be used in the browser, attempting to do so results in the following error: Unc ...

WooCommerce Checkout and My Account Edit Address now feature dynamic selectable fields for improved customization options

After finding a solution on Stack Overflow to show sub Areas dropdown based on the selected city in WooCommerce checkout, I customized the code for my specific requirements: function cities_areas_settings() { $text_domain = 'woocommerce'; ...

What is the best method for retrieving a child control from a TR element?

I am facing an issue with a hidden field inside each Tr in my template: <ItemTemplate> <tr style="" class="ui-selectee trClass ui-widget-content"> <td style="width: 100px"> <asp:HiddenField ID="idField" runat=" ...