What is the best way to create a function that can identify and change URLs within a JSON file?

I'm currently working on a function that will replace all URLs in a JSON with buttons that redirect to another function. The modified JSON, complete with the new buttons, will then be displayed on my website.

In my component.ts file, the section where the JSON is processed looks like this:

} else {
  this.downloading = false;
  this.container = <aContainer>json;
  this.loadedJson = JSON.stringify(json, null, 2);

Once the JSON is loaded, it is rendered on the website using the following code snippet in the component.html file:

<h3>Unrecognized JSON data:</h3>
<pre>{{loadedJson}}</pre>

I am considering using a regular expression (regExp) to identify and replace URLs within the JSON data, replacing them with 'url://'.

let regExp = /url:\/\//

Does anyone have suggestions on how I can create code that detects URLs and replaces them with buttons that link to another function?

Thank you for your help!

Answer №1

To manipulate the loadedJSON, you can implement a custom pipe and utilize property binding for innerHTML.

import { PipeTransform, Pipe } from "@angular/core";
import { DomSanitizer } from "@angular/platform-browser";

@Pipe({
  name: "transformURL",
  pure: false
})
export class TransformURLPipe implements PipeTransform {
  constructor(protected sanitizer: DomSanitizer) { }

  transform(value: any): any {
    if (value.length === 0) {
      return value;
    }
    return this.sanitizer.bypassSecurityTrustHtml(
      value.replace(/url:\/\//g, "<button type='button'>Test</button>")
    );
  }
}

HTML

<p [innerHTML]=" loadedJSON | transformURL"></p>

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

Ways to boost the efficiency of your Ionic 4 app development process

I have created an Ionic 4 app with over 50 screens, including components and popups. The build and live reload process is taking a lot of time, especially for minor UI changes. Is there a way to speed up the development process? Here are my Environment Se ...

Material-UI Slide component is encountering an issue where it is unable to access the style property of an undefined variable

Recently, I incorporated Material-UI Slide into my project and I'm curious about why the code functions correctly when written in this manner: {selectedItem && selectedItem.modal && selectedItem.modal.body ? ( selectedItem.modal.body.map((section ...

Help! My Angular CLI version 8.2.2 is displaying squares instead of the Font-awesome icons

I successfully added Font Awesome using the command npm install --save font-awesome angular-font-awesome from https://www.npmjs.com/package/angular-font-awesome. After linking it in my angular.json file: "styles": [ "src/styles.css", "node_modu ...

Accessing a specific data point from a Rest Api with React JS

How can I extract the value '00000000000000000000000000000000' that comes after clusters in the links->href in a Rest Api response? [{ "analysisUnits": [ { "links": [ { "href": "http://127 ...

Angular 11 now includes the ability to implement lazy loading for modules

Here is the configuration of my app-routing.module.ts: const routes: Routes = [ { path: 'login', component: LoginComponent }, { path: '', canActivate: [AuthGuard], component: HomeComponent, children ...

Explanation on retrieving JSON data from a ListView and passing it to another activity using SQLite in Android Studio

My goal is to navigate from the HOMESCREEN to a new activity, INTERNETSEARCHSCREEN, and then finally to the EDITINGSCREEN. I have successfully displayed JSON data on a listview but now I want to select a movie from the listview and display specific fields ...

ESLint detecting error with returning values in async arrow functions

Currently facing a minor inconvenience instead of a major problem. Here is the code snippet causing the issue: export const getLoginSession = async (req: NextApiRequest): Promise<undefined | User> => { const token = getTokenCookie(req) if (!t ...

PrimeNG Component Containing a Dynamic Dialog Instance

I am experiencing an issue with handling dynamic dialogs in PrimeNG. Is there a solution for managing actions on a dialog other than just using the close option? For instance, in the context of the Kendo-UI dialog example, I can specify the content.insta ...

Deactivate the chosen tab by clicking the Mat-Tab button

I was trying to implement a way to disable the selected mat-tab and its elements when a button is clicked, //HTML <mat-tab-group #tabGroup> <mat-tab *ngFor="let subject of subjects" [label]="subject.name"> {{ subject.name }} ...

Definition of TypeScript type representing the value of a key within an object

As I delve into defining custom typings for a navigation library using TypeScript, one challenge that has me stumped is creating a navigate function. This function needs to take the Screen's name as the first argument and the Screen's properties ...

I'm on the lookout for a component similar to angular-ui-tree that is compatible with angular

As a new developer, I am in search of a component similar to: But specifically for Angular 6, with all the same functionality (drag-and-drop capability, nested items, JSON structure, etc.). I have come across some components that either lack dragging fun ...

How can you enhance a component by including additional props alongside an existing onClick function?

As a newcomer to React and TypeScript, I've created a simple component that looks like this: const CloseButton = ({ onClick }: { onClick: MouseEventHandler }) => { const classes = useStyles(); return <CloseIcon className={classes.closeButto ...

Hide the value of a specific key in a JSON object

Looking for assistance with masking specific fields in JSON request and response logs. I want to be able to print the JSONs in the log while avoiding displaying certain secured fields. Here is an example: Original JSON: {"username":"user1","password":"12 ...

Can we extract unique values from a JSONObject in Java?

I have a JSON file containing 500,000 objects in the following format: "WORKORDER": [ { "Attributes": { "SITEID": { "content": "BEDFORD" }, " ...

Having trouble accessing props on children in TypeScript while using React.Children.toArray?

When using React.Children.toArray in Typescript, the props object on children is not detected. In order to address this issue, I am currently using any[] instead of ReactChild[], as props are not recognized on a array item when using the latter. Can someon ...

Tips for setting a default value in a generic function in TypeScript, where the default argument's type is determined by the generic parameter

One of my functions calls an API and accepts a parameter to limit the fields returned by the API: type MaximumApiResponse = { fieldA: string, fieldB: number } const f = async <U extends keyof MaximumApiResponse>( entity: number, prop ...

Reducing the size of XML files in ASP.NET 3.5 returned from WebMethods: Available solutions

Recently, I've come into possession of an ASP.NET web app built on .NET 3.5, along with its C# client components and a related JavaScript client. The server-side components currently use the default [WebMethod] serialization method, but due to the la ...

Page Breaks - Patience in anticipation of dataSource readiness

I am facing an issue with my pagination service and component. The dataSource appears empty when the page is loaded for the first time, but by the second time it is populated and I can display the dataTable and paginate successfully. Is there a workaround ...

Alternating the main access point from a separate module

I'm finding it difficult to understand why this should be so simple, but I just can't seem to solve this issue. Within my application, I have various root routes like login, events, and more. To manage the main menu functionality, I created a mo ...

Exploring the MEAN Stack for a Fresh Take on Single Page Application Development

Currently, I have implemented the hash location strategy on my Angular 4 client-side application. The refresh functionality works fine in development mode, but when I compile it to production mode using ng build -prod, the refresh feature breaks and the pa ...