Parse a string containing a selection of markdown by using regular expressions for tokenization

I need to tokenize a string using a regular expression that consists of markdown formatting. Specifically, bold text is denoted by **text** and italic text is denoted by _text_.

  • To tokenize the string "a _b_ c **d** _e", it should be split into ['a ', 'b', ' c', 'd', '_e'] (Note: each match needs to be stored in its own group).

I have successfully captured bold and italic groups using the regex /_(.+?)_|\*\*(.+?)\*\*/g, but I am trying to expand this regex to include all other text as well. Essentially, I want to capture everything inside **, everything inside _, and the rest of the text.

I attempted to add another case with /_(.+?)_|\*\*(.+?)\*\*|(.*)/g, but this ends up capturing the previous cases as well.


(A quick way to test this in the browser console: Array.from('a _b_ c **d** _e'.matchAll(/_(.+?)_|\*\*(.+?)\*\*/g)))

Answer №1

Utilize the unique unicode marker

/(?:\*{2})?_(\p{L}+)_(?:\*{2})?|(?:_)?\*{2}(\p{L}+)\*{2}(?:_)?|([*_\p{L}]+)/gu
:

displayResult(Array.from('x _y_ z **e** _f'.matchAll(/(?:\*{2})?_(\p{L}+)_(?:\*{2})?|(?:_)?\*{2}(\p{L}+)\*{2}(?:_)?|([*_\p{L}]+)/gu)))

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

"Regarding compatibility with different browsers - IE8, Firefox3.6, and Chrome: An inquiry on

Snippet of JavaScript Code: var httprequest = new XMLHttpRequest(); var time = new Date(); if (httprequest) { httprequest.onreadystatechange = function () { if (httprequest.readyState == 4) { alert("OK"); } }; httprequest.open("GET", ...

Selecting a particular item in a list depending on time using JavaScript, jQuery, or Angular

When working with a JSON file and binding it to list items, I have included a name/value pair in the json for each line indicating audio time, such as "time like 0, 5, 10 in seconds form". In my Cordova application, I am using a media plugin and implement ...

Show only half of the Google Charts

I have a code snippet that displays a chart with dimensions of 500x500. However, I only want to show half of the chart, like 500x250. But whenever I adjust the values in the div, it resizes the entire chart instead of just showing half. My goal is to hide ...

How can one use PHP to locate the strings that fall between the specified strings?

https://i.sstatic.net/USaMg.jpg Download and save as siva.txt Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt SIVA ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco lab ...

Make the download window appear automatically when downloading a file

How can I use JavaScript/TypeScript to prompt the browser to open the download window? My goal is to give users the ability to rename the file and select the download folder, as most downloads are saved directly in the default location. This is how I curr ...

Invoking a Jquery function through a GridView link

After attempting various methods for hours, I am throwing in the towel. It's possible that someone here might spot what I'm missing. I have a GridView containing a Delete button. Upon clicking on the ClientClick event, a javascript function is in ...

Efficient ways to temporarily store form data in React JS

When filling out a registration form and clicking on the terms and conditions link, the page redirects to that content. Upon returning to the registration page, all fields are empty and need to be filled in again from scratch. I am looking for a way to ha ...

Hiding both clear buttons in the MUI Autocomplete component on Chromium: A simple guide

The issue with the clear button is specific to Chromium; it does not appear in Firefox. Take a look at an example of a MUI React Autocomplete component displaying two clear buttons. Various solutions mentioned in this thread only hide the rightmost butto ...

Is searching for duplicate entries in an array using a specific key?

Below is an array structure: [ { "Date": "2020-07", "data": [ { "id": "35ebd073-600c-4be4-a750-41c4be5ed24a", "Date": "2020-07-03T00:00:00.000Z", ...

Utilize React's Context Provider to centrally manage all state while incorporating async calls

I am currently exploring more refined methods to establish a provider/consumer setup in which an asynchronous call is initiated from the provider, but the consumer does not need to handle state management. Within my context provider, I am fetching data to ...

Verify optional chaining support in Angular app for browsers

Within my Angular application, I am looking to verify if a client's browser supports optional chaining (es2020) in order to load a library that contains both a modern ES version and a legacy one. The issue arises when the Angular compiler (which I su ...

The positioning of CSS arrows using the "top" attribute is not relative to the top of the page when using absolute values

I am currently working on positioning the arrow in the screenshot using TypeScript calculations. However, I am facing an issue where the position is being determined based on the top of the black popup instead of the top of the screen. From the top of the ...

What is the best way to retrieve an error message within a sentence?

When using PHP code, I'm looking to extract error messages from the following sentences: $str='Data Error (400): {"error_messages":["Currency is not included in the list (IDR, SGD)"]} | Request url: https://app.sandbox.xxx.com/snap/v1/transactio ...

What is the proper way to incorporate an if statement within a return statement in React components?

I have encountered an issue while trying to map objects in my array. Everything works perfectly when mapping all the objects, but it becomes problematic when I attempt to map just one object from the array. Here is the code for my array: const slides = [ ...

Increasing values in Mongoose using $inc can be done by following these steps

I've been struggling to increment a field value using $inc in my code. My schema looks like this: var postSchema = mongoose.Schema({ title : { type: String, required: true }, body : { type: String, default: '' }, coun ...

Using AngularJS and Web API to generate a dropdown menu from a one-to-many relationship

I have two tables in my database: People and Payband. Let me simplify the relationship below: dbo.People PersonId : int (Primary Key) FirstName : string MiddleInitial: string LastName : string DateOfBirth: datetime PaybandId : int (Foreign Key) dbo.Payb ...

After cloning the variable from props, the Vue 3 Composition API variable becomes undefined

I have a main component containing code and tables, including a modal that is displayed based on a boolean value. The main component features the following modal: <ConfirmPaymentModal ref="confirmPaymentModal" :invoice="markAsPa ...

Verifying picture quality prior to transferring to a remote server

I am facing an issue with my image upload function to a remote server. The upload function works fine on its own, but when I integrate it into the size validation block, it stops working properly. <p> <input type="file" id="BtnBro ...

What is the definition of a type that has the potential to encompass any subtree within an object through recursive processes?

Consider the data structure below: const data = { animilia: { chordata: { mammalia: { carnivora: { canidae: { canis: 'lupus', vulpes: 'vulpe' } } } } }, ...

The Autocomplete feature from the @react-google-maps/api component seems to be malfunctioning as it returns

I'm encountering some difficulties with the Autocomplete component in @react-google-maps/api. While Autocomplete is working and displaying options, clicking on an option fills the input box but I'm only getting 'undefined' from the Plac ...