问题描述
有时我有一个可以接收这样的文本的组件:
I sometimes have a component that can receive text like this:
但是,如果它是一个链接,我想将其转换为URL.这样.
But I would like to convert it to a url if it is a link. Like this.
我阅读了此 SO答案,该建议建议使用第三方库,例如 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 install
.请注意,输入被视为纯文本,而输出则为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;
}
}
NB:如果需要指定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的方式(锚链接)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!