Is there a way to troubleshoot and adjust this regex to accurately replace asterisks within words?

I've been experimenting with regex. I came up with a regex pattern that converts * into <em>, similar to Markdown:

el = el.replace(/\*\b/g, '<em>')
el = el.replace(/\b\*|(\.|\,|\?|\!|\*|---|\.\.\.\s)\*/g, '$1</em>')

It works well in most cases. However, things get messy when you apply this regex to the following text:

Chicken teriy*ai*ki, r*ai*men noodles, spaghetti a la moneg*ai*sque.

It produces this result:

Chicken teriy<em>ai<em>ki, r<em>ai<em>men noodles, spaghetti a la moneg<em>ai<em>sque. And wait for me, often falling asleep.</em></em></em></em></em></em>

Is there a way to modify this regex so it gives an output more like this:

 Chicken teriy<em>ai</em>ki, r<em>ai</em>men noodles, spaghetti a la moneg<em>ai</em>sque. And wait for me, often falling asleep.

Answer №1

To combine the two branches in your second regex, you can merge them since they both end with the \* pattern. For example, you could use (\b|\.|,|\?|!|\*|---|\.{3}\s)\* (you could also simplify it further by merging the single character alternatives like \.|,|\?|!|\* into [.,?!*]) and then implement the following:

var s = "Chicken teriy*ai*ki, r*ai*men noodles, spaghetti a la moneg*ai*sque.";
console.log(
  s.replace(/\*\b([^]*?)(\b|[.,?!*]|---|\.{3}\s)\*/g, '<em>$1$2</em>') 
)

Details

  • \*\b - Represents a * followed by a word character (letter, digit, or underscore).
  • ([^]*?) - Group 1: Any 0+ characters, as few as possible (can be replaced with [\s\S] / [\d\D] / [\w\W] for more portability), up to the leftmost occurrence of
  • (\b|[.,?!*]|---|\.{3}\s) - Word boundary, ., ,, ?, !, *, ---, ... + whitespace
  • \* - Represents a * character.

Answer №2

Here is a solution that utilizes the use of regular expressions to wrap specific characters in * signs with em tags. Please note that this transformation will be applied universally to the entire input string provided.

 let str = "enclose these words with * symbols to emphasize them"
 str.replace(/\*(\w+)\*/g, "<em>$1</em>")

Answer №3

Pattern to use: \*([\w ^?.]*?)\*

Replacement code: <em>$1<\em>

el = el.replace(/\*([\w ^?.]*?)\*/g, '<em>$1<\em>')

Explore the Regex

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

Implementing multiple button functionalities and conditional statements in PHP

Despite my limited experience in PHP, I am working on a page with a basic setup that includes 4 buttons to send email reports regarding printer issues in our print labs to our service desk email. Although I have successfully coded the email sending functio ...

Is it necessary to bump the major version if I make updates to a react module that does not affect existing code functionality, but may cause Jest snapshot tests to break?

Imagine I am developing a module for a react component and currently working on a PR to introduce a new feature. Along with this new feature, I have also made changes to the component by refactoring it to eliminate certain internal parts that were previou ...

Enhancing ag-grid with alternating row group colors following row span

My data structure is shown below: https://i.stack.imgur.com/fy5tn.png The column spanning functionality in ag-grid is working for columns 1 and 2 as expected. However, I am looking to implement alternate row colors based on the values in column 2 (animal ...

Guidelines for passing multiple Javascript values to a C# action method

Assuming I have a piece of JavaScript code similar to the one shown in the image. I populate an array with multiple values and then pass this array to an action method in a controller. However, in the action method, I receive this array as an 'object& ...

Automatically populating and submitting a form after receiving search results via ajax

I have been struggling with this issue for a few days now and could really use some help from the experts here. I am new to sql, javascript, jquery, ajax, css, and php. Although I studied Computer Science in college 15 years ago, I seem to be missing some ...

Improvement in Select2 Change Event: Update the subsequent select2 box options based on the value change in the preceding select2 box

I need assistance with two select boxes, namely Category and Sub-category. My objective is to dynamically alter the available options in the subcategory box based upon the value selected in the category box. Additionally, I would like to load data for the ...

A guide on accessing information from nested arrays in JavaScript

I am having trouble retrieving data from a JavaScript array as it keeps showing undefined. Here is the code snippet: sabhaDetailsArrayTemp.forEach(element => { let arra = []; console.log(element) //return tmp.m_category_name ; arra = this.onSa ...

Having trouble importing the "@angular/material" module

I'm completely new to working with the MEAN stack and currently running into issues with Angular's material module. I am attempting to bring in the "@angular/material" module into my code, but encountering an error each time I try to import it. T ...

Issue encountered when making API requests in JavaScript that is not present when using Postman

Currently, I am developing a web application using express and one of the functionalities is exposed through an API with an endpoint on 'api/tone'. This API acts as a wrapper for one of Watson's services but I choose not to call them directl ...

Execute a script upon page load

Is there a way to trigger a script tag <script> immediately upon the website loading? I've experimented with various codes, but haven't found one that meets my needs. ...

Size of Output from RSA 2048 Encryption Using JSEncrypt

I've been under the impression that the output size of RSA 2048 bit encryption is 256 bytes. However, I keep getting 344 characters as output when using jsencrypt for testing. Can anyone shed some light on why this discrepancy exists? Tool used for o ...

The requested `GLIBC_2.28' version required by node cannot be located, leading to an inability to amplify the version

While there were numerous questions about this topic, I am specifically seeking solutions for amplify. Below are the logs from my amplify build: 2024-01-14T16:14:17.626Z [INFO]: # Cloning repository: <a href="/cdn-cgi/l/email-protection" class="__cf_em ...

What is the best way to obtain the accurate ClientID for my ASP.NET TextBox?

I've customized a Table subclass in my ASP.NET project that generates tables. This table utilizes a RowCreator class to format and create TableRows and TableCells, which are then called by MyTable. When MyTable calls rowCreator.CreateRow(), it receive ...

Updating the dropdown title to reflect the chosen dropdown value

I'm currently learning react and attempting to grasp the concept through tutorials. However, I am facing challenges in changing the title of a dropdown list based on the selected value. I am using react bootstrap for this task, but struggling to imple ...

Challenges arise when trying to load CSS on an EJS page in conjunction with using res.redirect()

When using Express with EJS, my base route is set as follows: router.get("/", productsData.getProducts); The "productsData" is sourced from my controllers page and the code snippet within that page is as follows: exports.getProducts = (req, res, next) => ...

Is it necessary to perform a specific action if the text within a div matches pre

I've been struggling to make this work properly. Even after removing the AJAX POST function, the issue persists. No alerts or any indication of what's going wrong. Check out the code on JSFiddle: HTML <div class="notification"> ...

Divide and conquer - meteorjs

I am currently utilizing the most recent version of Meteor. Meteor is designed to keep everything within the same directory structure, like this: MeteorProject -- .meteor -- client -- imports -- server -- test -- node_modules -- packa ...

Can we divide an animation in Three.js according to a model's individual parts?

Recently delving into the world of three.js, I have encountered a project with specific requirements: Load a humanoid gltf model Play various animations on the model Stop or play animation for only the head part of the gltf model without altering animatio ...

The button attached to the jQuery .toggle() function requires two clicks to activate

My objective is twofold: To dynamically load the Disqus script embed.js only when the "Show Comments" button is clicked. To toggle the visibility of the disqus_thread div using the same button while also changing the button's text. The issue I am f ...

In JavaScript, using window["functionName"](arguments) will result in a TypeError message saying that the function does not exist

When trying to execute an AJAX function based on the active tab in my application, everything works smoothly when I trigger the function after specific events. However, I encounter difficulties when attempting to call the function using a dynamically gener ...