In the realm of JavaScript and TypeScript, the task at hand is to locate '*' , '**' and '`' within a string and substitute them with <strong></strong> and <code></code>

As part of our string processing task, we are looking to apply formatting to text enclosed within '*' and '**' with <strong></strong>, and text surrounded by backticks with <code> </code>. I've implemented a logic that achieves this functionality flawlessly. However, the code seems overly complex for such a simple task. Below is the current implementation. Any suggestions for improvement would be greatly appreciated.

input =

"*within single star* and **within double start** and this is `backtick string`"

output =

"<strong>within single star</strong> and <strong>within double start</strong> and this is <code>backtick string</code>"

transform(data: any) {
        if (data) {
            const processDblStar = (input) => {
                const regExforDoubleStar = /(\*\*)+/gi;
                let i = 0;
                const result = input.replace(regExforDoubleStar, (match, matchedStr, offset) => {
                    i++;
                    return i % 2 === 0 ? '</strong>' : '<strong>';
                });
                return result;
            };

            const processSingleStar = (input) => {
                const regExforSingleStar = /(\*)+/gi;
                let i = 0;
                const result = input.replace(regExforSingleStar, (match, matchedStr, offset) => {
                    i++;
                    return i % 2 === 0 ? '</strong>' : '<strong>';
                });
                return result;
            };

            const processBackTick = (input) => {
                const regExforBackTick = /(\`)+/gi;
                let i = 0;
                const result = input.replace(regExforBackTick, (match, matchedStr, offset) => {
                    i++;
                    return i % 2 === 0 ? '</code>' : '<code>';
                });
                return result;
            };

            const processPipeline = (functions) => (inputStr) => functions.reduce((result, fn) => fn(result), inputStr);

            const funcArr: Function[] = [];
            if (data.indexOf('`') >= 0) {
                funcArr.push(processBackTick);
            }
            if (data.indexOf('*') >= 0) {
                funcArr.push(processSingleStar);
            }
            if (data.indexOf('**') >= 0) {
                funcArr.push(processDblStar);
            }

            processPipeline(funcArr)(data);
        }
    }

Answer №1

To extract all text enclosed between ** and *, regex can be utilized for grouping. The extracted group can then be referenced in the replacement string using $1. A similar approach can be applied to text enclosed within backticks, where the matched group is enclosed within <code></code> tags.

const str = '*within single star* and **within double start** and this is `backtick string`';

const processPipeline = s =>
   s.replace(/\*{1,2}(.*?)\*{1,2}/g, '<strong>$1</strong>')
    .replace(/`(.*?)`/g, '<code>$1</code>');

const res = processPipeline(str);
console.log(res);
document.body.innerHTML = res;

Answer №2

This may not be the most efficient method, but it's a concise code snippet.

var converter = new showdown.Converter();
var input = "*within single star* and **within double start** and this is `backtick string`";
var output = converter.makeHtml(input);
output = "\"" + output + "\""
output = output.replace(/<p>/g, "")
output = output.replace(/<\/p>/g, "")
output = output.replace(/<em>/g, "<strong>")
output = output.replace(/<\/em>/g, "</strong>")
console.log(output)
<script src="https://cdnjs.cloudflare.com/ajax/libs/showdown/1.9.0/showdown.min.js"></script>

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

Angular2/TypeScript Coding Guidelines

I am curious about the common practices and consensus among the Angular2 community when it comes to writing reusable code in TypeScript. I have gathered some information and questions related to Angular2 that I would like to discuss. Organizing Module/A ...

Create a timer that plays music when a button is pressed

My goal is to initiate a timer when a specific button is clicked. While there are many timers available that start upon page load, I have not been able to find one that begins upon clicking a button. Additionally, the timer must start at the same time as ...

Reversing text in mongodb

https://i.sstatic.net/Y61ML.png In my node.js and MongoDB 5 project, I am attempting to retrieve data where the field "TOTAL DUE" has a value other than '$0.00'. I have successfully selected records where "TOTAL DUE" equals '$0.00' usi ...

What is the best way to retrieve the input value from post.ejs?

app.js var express = require('express'); var bodyParser = require('body-parser'); var app = express(); var passport = require('passport'); var localStrategy = require('passport-local'); var axios = require("axi ...

Transform the post data into a JSON string within the controller

Hello everyone, I have a sample table that I want to share: <table class="table table-bordered" width="100%" cellspacing="0" id="tableID"> <thead> <tr> <th>A</th> <th>B</th> <th>C< ...

When validated, the Yup.date() function seamlessly converts a date into a string without including the timezone

Currently, I am integrating Yup with react-hook-form and have defined the following schema in Yup: const validationSchema = Yup.object({ installation: Yup.string().nullable().required("Required"), from_date: Yup.date() .max(new Date(), "Can ...

Ways to send data to a popup in svelte

Hey there, I could really use some assistance with my Svelte app. I'm trying to implement a modal and pass a parameter to the modal component in order to customize its content. However, when using the open() function of Modal, we only need to provide ...

Why does the lazy loading feature keep moving the background image around?

While trying to incorporate lazy loading on my website, I encountered an issue where the image position would change after it was fully loaded and made visible. I experimented with rearranging the order in which my JavaScript and CSS files were called, bu ...

Instead of receiving my custom JSON error message, Express is showing the server's default HTML error page when returning errors

I have set up a REST api on an Express server, with a React app for the front-end. The design includes sending JSON to the front-end in case of errors, which can be used to display error messages such as modals on the client side. Below is an example from ...

Issue: Headers cannot be set again once they have been sent during page reload

Whenever I attempt to refresh a specific page, I encounter an Error: Can't set headers after they are sent. Interestingly, when I click on a link to navigate to that page, the error doesn't occur. I have meticulously reviewed the sequence of even ...

Perform a jQuery function and SQL query when a selection is made in a dropdown menu

Struggling to execute a SQL query on drop-down menu selection. Here's my current code: <script> $('#templateid').change(function(DoUpdateOnSelect) { $.post('page.edit.php?page_id=(-->Need help in retrieving this id from the pa ...

Optimal method for writing to JSON file in NodeJS 10 and Angular 7?

Not sure if this question fits here, but it's really bothering me. Currently using Node v10.16.0. Apologies! With Angular 7, fs no longer functions - what is the optimal method to write to a JSON file? Importing a JSON file is now simple, but how ca ...

Tips for creating Selenium code to verify the asterisk symbol

Looking to create Selenium code for validating the presence of asterisks with mandatory fields such as First Name*, Last Name*, Enter Address*, and Enter Phone Number*. The validation needs to confirm the asterisk appears after each field name. Currently ...

Error encountered when using the Jquery append function: Anticipated ')' issue

While working on my PHP file, I encountered an issue with an AJAX request. The request is returning the correct value, however, when attempting to use the append function in jQuery, it results in an error being displayed in the console. $.ajax({ ...

Using javascript to quickly change the background to a transparent color

I am in the process of designing a header for my website and I would like to make the background transparent automatically when the page loads using JavaScript. So far, I have attempted several methods but none seem to be working as desired. The CSS styles ...

Nested setInterval in JavaScript refers to the practice of nesting

I am attempting to create nested timed code using setInterval. However, my initial approach does not produce any response from Chrome and Firefox: setInterval(function() { console.log('1'); setInterval(function(){ console.log(& ...

Changing the names of the remaining variables while object destructuring in TypeScript

UPDATE: I have created an issue regarding this topic on github: https://github.com/Microsoft/TypeScript/issues/21265 It appears that the syntax { ...other: xother } is not valid in JavaScript or TypeScript, and should not compile. Initial Query: C ...

I'm having trouble understanding why my Javascript validation suddenly stopped functioning. Can anyone assist me in troubleshooting this issue?

I have been working on this webpage for a school project for a few days, and it was running smoothly until about 10 minutes ago. The only change I made was adding an extra JavaScript validation. Now, when I try to register by clicking the "register" butt ...

Incorporating an interface into a data property within a router using TypeScript and Angular

Within the app-routing-module.ts file, utilizing the data property allows us to include custom fields/variables as shown below: ... { path: 'admin-board', loadChildren: './admin-board/admin-board.module#AdminBoardPageModule', dat ...

Displaying the product quantity counter in the shopping cart immediately after adding the item

My website has a shopping cart quantity counter that doesn't update immediately when a product is added. Instead, it requires a page reload or navigation to another page for the change to be reflected. I would like the quantity counter to show the pro ...