通过regex匹配ahref标记,然后转换为字符串

match ahref tags via regex then convert into string

本文关键字:然后 转换 字符串 标记 regex 匹配 ahref 通过      更新时间:2023-12-11

所以我在后台发出api请求时收到了这个字符串格式(这是flash的遗留代码,我们必须将其转换为html):

 <TextFlow whiteSpaceCollapse="preserve" version="2.0.0" xmlns="http://ns.adobe.com/textLayout/2008"><p><a href="http://yahoo.com"><span>yahoo</span></a><span> </span><a href="http://google.com"><span>google</span></a></p></TextFlow>

在客户端,我被要求去掉html标签(除了ahref标签)并显示它们。因此,预期的结果是:

<a href="http://yahoo.com"><span>yahoo</span></a>
<a href="http://google.com"><span>google</span></a>

到目前为止,我所做的是:

var htmlString = this.model.get( 'FolderDescription' );
htmlString.replace(/href="([^'''"]+)/g, function( match ) {
    matches.push( match );
} )

我得到的输出是:

 ["href="http://yahoo.com", "href="http://google.com"]

如何显示ahref标记,包括标记内的文本?

您就快到了。只需将所有字符匹配到下一个关闭锚标记即可。

<a'b[^<>]*'bhref="[^'''"]+".*?<'/a>

演示

> var s = '<TextFlow whiteSpaceCollapse="preserve" version="2.0.0" xmlns="http://ns.adobe.com/textLayout/2008"><p><a href="http://yahoo.com"><span>yahoo</span></a><span> </span><a href="http://google.com"><span>google</span></a></p></TextFlow>'
undefined
> s.match(/<a'b[^<>]*'bhref="([^'''"]+)".*?<'/a>/g)
[ '<a href="http://yahoo.com"><span>yahoo</span></a>',
  '<a href="http://google.com"><span>google</span></a>' ]

使用捕获组的正则表达式:

href="(['w'/.':]*)"
相关文章: