Angular2 将纯文本转换为 url 的方式(锚链接) [英] Angular2 way of converting plain text to url (anchor links)

查看:23
本文介绍了Angular2 将纯文本转换为 url 的方式(锚链接)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有时有一个组件可以接收这样的文本:

I sometimes have a component that can receive text like this:

文本 www.website.com

text www.website.com

但是如果它是链接,我想将其转换为网址.像这样.

But I would like to convert it to a url if it is a link. Like this.

文本 www.website.com

我读过这个 SO answer 建议使用 3rd 方库,例如 anchorme.有没有办法以 angular2 的方式做到这一点?

I read this SO answer that suggests using 3rd party libs such as anchorme. Is there anywway to do it the angular2 way?

推荐答案

使用简单的正则表达式修改 HTML 内容存在许多问题.

There are numerous problems with using simple regexes to modify HTML content.

这是一种使用 linkifyjs 模块的方法,您需要npm安装.请注意,输入被视为纯文本,而输出是 HTML 文本.

Here's an approach that uses the linkifyjs module, which you need to npm install. Do notice that the input is considered plain text, while output is HTML text.

import { Pipe, PipeTransform } from '@angular/core';
import linkifyStr from 'linkifyjs/string';

@Pipe({name: 'linkify'})
export class LinkifyPipe implements PipeTransform {
  transform(str: string): string {
    return str ? linkifyStr(str, {target: '_system'}) : str;
  }
}

注意:如果您需要指定target 属性,请添加例如.{target: '_system'} 作为 linkifyStr 的第二个参数.

NB: If you need to specify the target attributes, add eg. {target: '_system'} as a second parameter to linkifyStr.

这篇关于Angular2 将纯文本转换为 url 的方式(锚链接)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆