Swapping characters from the beginning and end of a specific string

Consider the following scenario:

b*any string here*

If this pattern is present, I would like to substitute b* at the beginning with <b>, and the * at the end with </b> (Ignore the backslash for SO site escaping).

It's possible that there are multiple occurrences:

b*any string here* and then b*string b*.

However, these cases should not be addressed:

b*foo bar
foo bar*
bb*foo bar* (b does not follow a space or start of string).

Here is what I have so far:

(?<=b\*)(.*?)(?=\*)

While this provides the text between, I am encountering challenges in making the replacement.

Answer №1

To maintain specific text in a string, utilize the String#replace method with proper text capturing:

var result = theString.replace(/\bb\*(.*?)\*/g, "<b>$1</b>");

In the regex pattern, the use of \b signifies a word boundary, ensuring that only standalone instances of b are matched. The expression $1 represents the first captured group (.*?).

For example:

var str1 = "b*any string here* and after that b*string b*.";

var str2 = `b*foo bar
foo bar*
bb*foo bar* (b is not after a whitespace or beginning of string).`;

console.log(str1.replace(/\bb\*(.*?)\*/g, "<b>$1</b>"));

console.log(str2.replace(/\bb\*(.*?)\*/g, "<b>$1</b>"));

Answer №2

If you want to highlight text wrapped in asterisks using a regular expression, you can do so with \b(?:\*)(.+?)(?:\*).

const highlightedText = yourString.replace(/\b(?:\*)(.+?)(?:\*)/, "<b>$1</b>");

To see this in action, check out the 'Replace' tab at https://regex101.com/.

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

Can you explain the distinction between these two MongoDB $regex formats?

Suppose I am looking to find users with the word "foo" in their username. Is there a significant distinction between these two queries? db.users.findOne({"username" : {$regex : ".*foo.*"}}) And: db.users.findOne({"username" : {$regex : "foo"}}) Both ap ...

What is the best way to include a new array at the beginning of a lexicographically sorted array?

After lexicographically sorting an array, I am trying to figure out how to add values from another array "cityOfTheMoscow" first and then maintain the lexigraphical order. However, while using the code snippet below: result.unshift(...self.cityOfTheMoscow ...

Enhance your website with a unique hover and left-click style inspired by the functionality of file explorer

I have a set of items like this: I am trying to replicate the functionality of a file explorer in terms of item selection. To clarify, I aim to create a feature where hovering over an item and left-clicking it would generate a virtual rectangle to select ...

Angular routing template failing to execute inline JavaScript code

I'm facing an issue with my Angular.js routing implementation. I have successfully displayed the HTML code in templates using angular.js, but now I am encountering a problem with my template structure: <div id="map_canvas" style="width:95%; heigh ...

Previewing the small version, loading the URL into a container

Currently, I am working with jQuery's .load(url, ...) function to bring in a url and display it within a div. However, I am facing an issue where the result needs to be resized in order to fit correctly within the layout. Can anyone provide guidance o ...

What is the best approach to alter a user's message depending on the form's ID that was used for submission?

I currently have two separate screens that each serve a specific purpose, where only one can be open at any given time. First is the login form: <form action="/Account/Login" id="login-form" class="form" method="post"> <butto ...

The map fails to load on the HTML page

I am struggling to load a map into my HTML page from a file located in the app folder. Despite using the correct code for inserting the map, it still does not load properly. <!-- Contact section start --> <div id="contact" class="contact"> ...

When implementing asynchronous form control validation in Angular 2, several API requests are triggered

Can anyone help me with adding async validation using a FormControl? For every keypress, I am receiving multiple responses and it seems like an extra request is triggered whenever I type or remove a character in the form control. code-snippets.component.t ...

Determine whether an element is currently focused using a Vue.js directive

I'm attempting to verify if an element is currently in focus, specifically an input field, and then apply a class to another element. This is the code I have been working on, but for some reason the hasFocus() function isn't functioning as expect ...

Develop a dynamic thunk and additional reducer to efficiently handle multiple API calls and retrieve data

Using Redux and Redux-Toolkit, I aim to streamline my code by implementing a single asynchronous Thunk and extra reducer for multiple requests. Below is the setup for both the company and client slices: import { createSlice, createAsyncThunk } from &apos ...

Developing in Node.js involves setting a specific timezone while creating a date

I feel like I'm overcomplicating things here. My server is running on nodejs, and the front-end is sending me an offset. What I need is to determine the UTC equivalent of yesterday (or today, or last week) based on this offset. Currently, my code l ...

Tips for creating a static background when displaying a modal popup in AngularJS

Incorporating a modal popup to modify a row within a grid view has been my recent task. Leveraging the row.getProperty() function, I successfully extracted the row values within the modal. However, an inconvenience emerged when attempting to edit a value ...

Obtaining a cookie from a browser that has been dropped by a different application

Is there a way to check if a user is logged in by hitting an application URL programmatically using Java or JSP? It generates a cookie named xyz for logged-in users in the browser. For some reason, every time I call the URL from my Java code, it doesn&apo ...

Steps for creating a node.js and ejs file to deploy on 000webhost

I have developed a simple todo-app using node.js and ejs templating. My goal is to host it using 000webhost, a free web-hosting service. I successfully hosted a react app for free on this platform by running "npm run build", which converted the ...

Having trouble generating an image with JavaScript

I am currently working on incorporating an image onto a webpage using JavaScript. Surprisingly, even the alert('This function works!') is not displaying anything! What could be causing this issue? Please assist! <!DOCTYPE html> <html> ...

Incorporating an external TypeScript script into JavaScript

If I have a TypeScript file named test.ts containing the code below: private method(){ //some operations } How can I access the "method" function within a JavaScript file? ...

Receiving a JavaScript object from an on-click event and passing it to a function does not allow it to be submitted as part

Appreciate any insights... I handle the submission of a form button click: $('.saveItem').on( 'click', function(e) { submitItemSave(true, e); }); When the user-defined function is called on click, the event, e, is passed in: func ...

What is the best way to modify the size of a canvas element while maintaining effectiveness?

I've encountered an issue while using Canvas to create a pie chart with chart.js. Despite adjusting the dimensions of the canvas element, it continues to take up the entire page. <canvas id="myChart" height ="200" width="200"></can ...

Pause the audio using jQuery when the slide changes

I have a Drupal website with a slider that includes an audio player on each slide. I need the audio to stop whenever the slide changes. The slider plugin I'm using is owlCarousel. Here is my current code: $("#owl-demo").owlCarousel({ afterAction: ...

using the useEffect hook to create a loop that runs infinitely

For my project, I am working on updating data in firebase. The issue that I'm facing is that the data seems to be constantly looping, causing potential crashes. Is there a way to stop this loop and prevent any crashing? import "./App.css"; ...