Alter text within a string situated between two distinct characters

I have the following sentence with embedded links that I want to format:

text = "Lorem ipsum dolor sit amet, [Link 1|www.example1.com] sadipscing elitr, sed diam nonumy [Link 2|www.example2.com] tempor invidunt ut labore et [Link 3|www.example3.com] magna"

The desired output should be:

newText = "Lorem ipsum dolor sit amet, <a href=www.example1.com target="_blank">Link 1</a> sadipscing elitr, sed diam nonumy <a href=www.example2.com target="_blank">Link 2</a> tempor invidunt ut labore et <a href=www.example3.com target="_blank">Link 3</a> magna"

The code provided only replaces the first link (Link 1), but Links 2 and 3 are not affected:

const urlTextChain = text.substring(text.indexOf("[") + 1, text.indexOf("]"));

if (urlTextChain) {
  const textUrl = urlTextChain.substring(0, urlTextChain.lastIndexOf("|"));
  const url = urlTextChain.substring(urlTextChain.indexOf("|") + 1);
  const link = "<a href=" + url + " target=" + '"_blank"' + ">" + textUrl + "</a>";
  let newText = text.replace(urlTextChain, link);
  newText = newText.replace('[', '');
  newText = newText.replace("]", '');
  return newText;
}

Answer №1

Check out MDN's guide on using String.prototype.replace Learn more about RegExp from MDN

Utilize the power of RegExp for text replacement.

p1 points to the content within the first set of parentheses, while p2 represents the value inside the second pair of parentheses.

const text =
  'Lorem ipsum dolor sit amet, [Link 1|www.example1.com] sadipscing elitr, sed diam nonumy [Link 2|www.example2.com] tempor invidunt ut labore et [Link 3|www.example3.com] magna'

const convertLinkFromText = (txt) => {
  const reg = new RegExp(/\[(.*?)\|(.*?)\]/, 'gi')

  return txt.replace(reg, (match, p1, p2) => {
    return `<a href="${p2}" target="_blank">${p1}</a>`
  })
}

const newText = convertLinkFromText(text)

console.log(newText)

Answer №2

Here's a great opportunity to showcase the power of regular expressions. Give this approach a try:

const originalText = 'Lorem ipsum dolor sit amet, [Link 1|www.example1.com] sadipscing elitr, sed diam nonumy [Link 2|www.example2.com] tempor invidunt ut labore et [Link 3|www.example3.com] magna';

const modifiedText = originalText.replace(/\[([^|\]]+)\|([^\]]+)\]/g, '<a href="$2" target="_blank">$1</a>');

This will result in:

Lorem ipsum dolor sit amet, <a href="www.example1.com" target="_blank">Link 1</a> sadipscing elitr, sed diam nonumy <a href="www.example2.com" target="_blank">Link 2</a> tempor invidunt ut labore et <a href="www.example3.com" target="_blank">Link 3</a> magna

Answer №3

A useful function to consider is the replaceAll method, which operates in a similar manner to the replace method.

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

Generate menu options in real-time

I have developed a React single page application using the NASA Picture of the Day API. I am looking to incorporate a drawer feature that displays a history of previously shown images, but only showing their dates. However, I am unsure of how to dynamical ...

What is the best method to locate an element<T> within an Array[T] when <T> is an enum?

I've recently started learning TypeScript and exploring its functionalities. I could use some assistance in deepening my understanding. Within our angular2 application, we have defined an enum for privileges as follows: export enum UserPrivileges{ ...

What is the reason behind receiving a CSS warning stating "Expected color but found '0' " when using Phaser's setText() function?

Here's how I created my text object: statusBarHP.text = game.add.text(0, 0, '', { font:"16px Arial", fill:"#ffffff", stroke:"#000000", strokeThickness:2 }); For the object that holds the text: statusBarHP = game.add.sprite ...

"Sequelize will pause and wait for the loop to finish before executing the

As someone with a background in PHP, I'm finding the concept of callbacks a bit challenging to grasp. Essentially, I need to retrieve some rows and then iterate through them to compare against another model (in a different database). However, I want ...

Issue with 'firebase.auth is not defined' error following SDK update

I've been using the Firebase JS sdk for web development without any issues for a year now. However, after recently updating my code from version 5.3.1 to the latest 6.5.0 SDK version, I encountered the following error: TypeError: firebase.auth is no ...

Three.js - Controlling Visibility of Text in troika-three-text with Clipping Planes

Has anyone successfully clipped troika-three-text for threejs using clipping planes? I'm having trouble getting it to work. import { Text } from 'troika-three-text' const minClippingPlane = new THREE.Plane(new THREE.Vector3(0, -1, 0), 1) c ...

Enhance your user interface by adding a tooltip above a button

I am currently working on creating a button that can copy content from a variable into the clipboard using TypeScript and Material-UI. Here is what I have tried: const [copySuccess, setCopySuccess] = useState(''); const copyToClipBoard = async ( ...

Issues with audio and video playback intermittently occurring on Sencha Touch 2

As a beginner with Sencha Touch 2, I am currently working on uploading images onto an iPad using Xcode. My app has audio playing on the home screen, and I want the video to start playing and the audio to stop when a specific tab is selected. However, the ...

Searching for the element that triggered the event using jQuery or JavaScript

Can anyone offer tips on how to use console.log to identify the element that triggered a hover event? I'm trying to debug an issue specifically on iOS. I'm not looking to locate the specific item that the action was performed on, but rather what ...

Utilizing ngModel within the controller of a custom directive in Angular, instead of the link function

Is there a way to require and use ngModel inside the controller of a custom Angular directive without using the link function? I have seen examples that use the link function, but I want to know if it's possible to access ngModel inside the directive ...

Creating a unique directive to customize the height

I'm currently working on a directive called appHeaderResize, which is designed to calculate the height of both the <app-online-header> component and the <app-navigation> component. Below is the code snippet: <div class="sticky" appHe ...

The identification number is not used to update Mongo DB

When attempting to use the MongoDB driver in Node.js to update a document, I encountered an issue where the log indicated that the update was successful, but the data did not reflect the changes. Specifically, despite trying to update the document using it ...

Issue: angular2-cookies/core.js file could not be found in my Angular2 ASP.NET Core application

After spending 2 hours searching for the source of my error, I have decided to seek help here. The error message I am encountering is: "angular2-cookies/core.js not found" I have already installed angular2-cookie correctly using npm. Below is the code ...

Shuffle the contents of various div elements, conceal one, reveal another

I am currently working with a menu that uses the loadContent function to load pages into the #main div. This allows me to change the content of the page while keeping the menu intact. <ul> <li class="page1" onclick="loadContent('page1.php ...

Spooky results displayed on website from NightmareJS

Is there a way to display the output from nightmareJS onto a webpage when a button is clicked using HTML, CSS, and JS? This is my nightmareJS code: var Nightmare = require('nightmare'); var nightmare = Nightmare({ show: false}) nightmare .go ...

Angular: Exploring the differences between $rootScope variable and event handling

I have a dilemma with an app that handles user logins. As is common in many apps, I need to alter the header once the user logs in. The main file (index.html) utilizes ng-include to incorporate the header.html I've come across two potential solution ...

Issues with setting default values for controls in Angular's reactive forms

I need help with displaying a preselected option on my dropdown list. I have set the value to preSelectedLegalType in the ngOnInit function, but for some reason it is not getting displayed. How can I make sure this value is displayed? The TypeScript file ...

Triggering an event from a component to its parent module resulting in an exception situation

Here is my app.component.ts code: import { Component, Input, OnInit, OnChanges, SimpleChanges} from '@angular/core'; import {Counter } from './counter' @Component({ selector: 'my-app', template: ` <custom-counter [ ...

Dealing with a JavaScript Problem on Wordpress Using AJAX

Struggling with transitioning a website from Drupal to WordPress, I encountered an issue with a page that utilizes AJAX. A user followed a tutorial on implementing AJAX using JavaScript, PHP, and MySQL. Even though the AJAX functionality works fine on Drup ...

Express/NodeJS encountering a CORS problem, causing services to be inaccessible in Internet Explorer

Currently, I am working on a REST-based service implemented in Express/NodeJS. The code includes CORS (Cross Origin Resource Sharing) implementation to allow services to be consumed from browsers like Chrome and Firefox. However, there seems to be an issue ...