Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

221
Views
¿Cómo puedo dividir una cadena en una matriz de elementos que son y no son enlaces?

No puedo encontrar una buena solución para mi problema. Así que tengo que crear una vista que esté envuelta por div en el que se pueda hacer clic. Mi contenido será solo texto sin formato mezclado con URL en las que se puede hacer clic; el problema es que hacer clic en el enlace también activa el método de envolver div; este es un comportamiento no deseado, por lo que tengo que agregar event.stopPropagation() en el elemento <a> .

Esta solución no funciona (no hay forma de manejar el clic en el componente, simplemente no funciona; toma todo lo que paso para (click)=.... como cadena incluso cuando uso ${ } ):

 @Pipe({ name: 'urlify' }) export class UrlifyPipe implements PipeTransform { transform(text: any): any { const urlRegex = /(\b(https?|ftp|file):\/\/[-AZ\d+&@#/%?=~_|!:,.;]*[-AZ\d+&@#/%=~_|])/ig; return text.replace(urlRegex, (url) => { return '<a href="' + url + '">' + url + '</a>'; }); } }

Así que mi idea es crear un componente con entrada de texto. En init quiero dividir el texto de esta manera:

Texto de ejemplo: Lorem Ipsum is simply dummy text www.wykop.pl of the printing and typesetting industry https://sadistic.pl.

Matriz buscada:

 [ "Lorem Ipsum is simply dummy text ", "www.wykop.pl ", "of the printing and typesetting industry " "https://sadistic.pl" "." ]

Y luego, en el html, quiero usar ngFor y ngCase para crear el elemento adecuado y luego podría agregar fácilmente stopPropagation para el elemento <a> . ¿Alguien puede ayudarme a dividir el texto de esta manera? ¿O tal vez tienes otras ideas para mi problema?

about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

Creo que podría usar el método dividido con expresiones regulares y mantener el delimitador:

 const text = 'Lorem Ipsum is simply dummy text www.wykop.pl of the printing and typesetting industry https://sadistic.pl.'; const urlRegex = /([https?|ftp|file|]+[:\/\/]+[-AZ\d+&@#/%?=~_|!:,.;]*[-AZ\d+&@#/%=~_|]|[www][-AZ\d+&@#/%?=~_|!:,.;]*[-AZ\d+&@#/%=~_|])/gi; const result = text.split(urlRegex); console.log(result);

PS un poco modificado tu expresión regular

about 4 years ago · Juan Pablo Isaza Report

0

Puede usar onclick directamente en el elemento <a> para evitar la propagación:

 import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: `<div (click)="wrap()" [innerHtml]="text | urlify"></div>`, styleUrls: ['./app.component.css'], }) export class AppComponent { text = 'Lorem Ipsum is simply dummy text www.wykop.pl of the printing and typesetting industry https://google.com'; wrap() { console.log('wrap click'); } }
 import { Pipe, PipeTransform } from '@angular/core'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; @Pipe({ name: 'urlify', }) export class UrlifyPipe implements PipeTransform { constructor(private _sanitizer: DomSanitizer) {} transform(value: any, args?: any): SafeHtml { const urlRegex = /(\b(https?|ftp|file):\/\/[-AZ\d+&@#/%?=~_|!:,.;]*[-AZ\d+&@#/%=~_|])/gi; const html = value.replace( urlRegex, (url) => `<a href="#${url}" onclick="event.stopPropagation();">${url}</a>` ); return this._sanitizer.bypassSecurityTrustHtml(html); } }

ejemplo: StackBlitz

o puede implementar directivas estructurales de brujas algo como esto:

 <app-text [text]="text"> <ng-template *appHref="let href"> <a [href]="href" (click)="$event.stopPropagation()">{{ href }}</a> </ng-template> <ng-template *appText="let text"> <span>{{ text }}</span> </ng-template> </app-text>

(@Yan Koshelev, ¿así?)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!