Alter regular expression matches within the new string replacement

I am having an issue with using regex to extract URLs from a text and then modifying all the matches within the replacement string using a function. Below is a simplified example of what I am trying to accomplish. Is it possible to achieve something like this?

var exp = /\b((http:\/\/|https:\/\/)[\S]*)/g;
text = text.replace(exp, "<a href=\"$1\" title=\""+parseUri("$1").host+"\"></a>");

Answer â„–1

Include a custom function in the 2nd parameter of the .replace method:

var exp = /\bhttps?:\/\/[\S]*/g;
text = text.replace(exp, function ($0) {
    return '<a href="' + $0 + '" title="' + parseUri($0).host + '"></a>'
});

(Keep in mind that $0 is just a placeholder name and can be changed).

Refer to the documentation of String.replace on MDN for details on the arguments required in the replacement function. The initial argument represents the entire captured text by the regex pattern. Subsequently, any additional arguments correspond to the content captured by individual groups in the regex.

I have also modified the regex pattern slightly by removing \b, as it is an assertion and does not consume any actual text.

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 action 'addSection' is restricted to private access and can only be utilized internally by the class named 'File'

const versionList = Object.keys(releaseNote) for (const key of versionList) { // Skip a version if none of its release notes are chosen for cherry-picking. const shouldInclude = cherryPick[key].some(Boolean) if (!shouldInclude) { continue } // Include vers ...

Do identical files stored in separate locations produce unique sha1 hashes?

var crypto = require('crypto'); var fs = require('fs'); var file1 = process.argv[2]; var file2 = process.argv[3]; var sha1sum = function(input){ return crypto.createHash('sha1').update(JSON.stringify(input)).digest(' ...

Why is the Javascript code outputting undefined and NaN during execution?

As a newcomer to the world of javascript, I am venturing into learning its fundamental concepts. In my quest for knowledge, I've dabbled in file reading and came up with a small script which you can find below. // Incorporating the fs (filesystem) mo ...

Adjusting HTML5 drag height while resizing the window

Code conundrum: var dragHeight = window.innerHeight - parseInt(jQuery("#drag_area").css("margin-top")) - 5;. It sets the drag height based on browser size, but there's a glitch. If I start with a non-maximized browser and then maximize it, the drag he ...

Crafting redirect rules in React that avoid redirecting to the same route

In my project, there is a file named AuthenticatedRoute.tsx, which serves as a template for all the protected/authenticated routes in my Router.tsx file. export default ({ component: C, authUser: A, path: P, exact: E }: { component, authUser, path, ex ...

What are the steps to implement the jQuery slide menu effect on a website?

When visiting the website , you may notice a symbol positioned in the top left corner of the site. By clicking on this symbol, a sleek div will slide out. How can this type of animation be achieved through javascript or jquery? ...

Is it possible to transform an array into a JSON file and securely store/upload it in an AWS S3 bucket?

Recently, I started exploring aws and its capabilities. Currently, my focus is on developing a web application that allows users to input text in two separate fields. Subsequently, this text will be converted into a Json file and stored in the S3 bucket. ...

Matching Regex Patterns for Parents and Children

Regex has always been a struggle for me, so I could really use some guidance. I'm attempting to create opening and closing 'tags' with the same regex permitted inside these tags. For example, a tag might look like: <: tagname("[captur ...

Challenges with resizing windows in jQuery

I'm currently working on optimizing my jQuery code and everything seems to be running smoothly so far: jQuery $(document).ready(function(){ $(".fadeinbg").click(function(){ $("#content").fadeIn(); }); var height = $(window).height() ...

The elegant-admin template's mobile navigation toggle is missing

I recently downloaded an admin theme and added the CSS to my Django static files. However, after doing so, the mobile toggle feature disappeared. I double-checked all the CSS and JS links in the index template, and they are correctly linked to the paths, b ...

The connection between ng-model and ng-repeat, and the comprehension of $scope

<!DOCTYPE html> <html> <head> <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script> </head> <body> <div ng-app="myApp" ng-controller="customersCtrl"> <ul& ...

Utilize a Random Color Generator to Match Background Color with Border Color in Full Calendar

I'm currently developing a full calendar to showcase a clear and aesthetically pleasing schedule for my client. I am attempting to assign a unique color to each event by generating random colors on every page load using codes. However, I have encounte ...

Exploring the world of XD plugins, utilizing npm packages and Node.js APIs

Is it feasible to integrate npm packages and Node.js APIs into my Adobe XD plugin development process? ...

Access the values within an array located inside a data object by utilizing ng Repeat function

Attempting to utilize ng repeat for extracting values from an array. Below is the HTML code: <ion-list ng-repeat="item in locationresult"> <ion-item > <ion-checkbox ng-repeat="innerItem in item.loc[$index]"> ...

JSNI is failing to execute external function calls properly

I need help converting this JavaScript code into JSNI code. Required Scripts <script src="jquery-1.11.2.min.js"></script> <script src="jquery.typeahead.min.js"></script> <script src="autocompletetest/autocompletetest.nocache.js ...

What is the method for obtaining the number of weeks since the epoch? Is it possible to

Currently, I am setting up a DynamoDb store for weekly reporting. My idea is to use the week number since 1970 as a unique identifier for each report record, similar to epoch milliseconds. Here are some questions I have: How can I determine the current w ...

CSS/SCSS/JS: Adjusting header height dynamically while keeping it fixed at the

Check out my Codepen demo here: https://codepen.io/nickfindley/pen/dJqMQW I am seeking to replicate the current behavior of the page without specifying a fixed height for the header. The goal is to make the header adjust dynamically based on the content, ...

Maintaining AngularJS Authentication Securengular: Ensuring

I need to find the ideal architectural solution. Below is the HTML code I currently have: <body ng-controller="individualFootprintController as $ctrl"> <div ng-hide="$ctrl.authenticated"> <h1>Login</h1> Wit ...

Encountering a Node V18 Peer Dependency Conflicté”™

Can someone please help me understand what's causing this error? Every time I try to install a dependency, this keeps popping up. I'm completely lost and unsure of what's happening. npm ERR! 1 more (the root project) npm ERR! peer ...

Encountering an undefined error while attempting to retrieve an object from an array by index in Angular

Once the page is loaded, it retrieves data on countries from my rest api. When a user selects a country, it then loads the corresponding cities for that country. Everything is functioning properly up to this point, however, upon opening the page, the city ...