Rumah > Soal Jawab > teks badan
现在有一段字符串
哈哈啊哈 qq.com/da/7213971209381023812038-102931-2093-129312931=239 baka 163.com 无语 sohu.net 大苏打 yahoo.com/asdasd/72093802381-293-1293-12931-923
在后台转换成的HTML链接
哈哈啊哈
<a rel="nofollow" href="http://qq.com/da/72" title="http://qq.com/da/7213971209381023812038-102931-2093-129312931=239" target="_blank">qq.com/da/7213971209381023812038-102931-2093-129312931=239</a>
baka
<a rel="nofollow" href="http://163.com" title="http://163.com" target="_blank">163.com</a>
无语
<a rel="nofollow" href="http://sohu.net" title="http://sohu.net" target="_blank">sohu.net</a>
大苏打
<a rel="nofollow" href="http://yahoo.com/as" title="http://yahoo.com/asdasd/72093802381-293-1293-12931-923" target="_blank">yahoo.com/asdasd/72093802381-293-1293-12931-923</a>
现在想截取链接的文本长度,但title和href属性保持不变,成这样效果
哈哈啊哈
<a rel="nofollow" href="http://qq.com/da/72" title="http://qq.com/da/7213971209381023812038-102931-2093-129312931=239" target="_blank">qq.com/da/</a>
baka
<a rel="nofollow" href="http://163.com" title="http://163.com" target="_blank">163.com</a>
无语
<a rel="nofollow" href="http://sohu.net" title="http://sohu.net" target="_blank">sohu.net</a>
大苏打
<a rel="nofollow" href="http://yahoo.com/as" title="http://yahoo.com/asdasd/72093802381-293-1293-12931-923" target="_blank">yahoo.com/</a>
代码效果见 http://jsfiddle.net/deathfang/KzEzy/ 第三块就是最终实现效果,链接匹配转换用的是twitter里的代码
var wraplinkAttrs = {
urlTarget: "_blank",
rel: "nofollow",
}
var content = document.querySelector('.o_text').innerText;
var post = {},
links = twitterText.extractUrls(content);
post.content = links.length ?
twitterText.autoLinkEntities(
content, twitterText.extractUrlsWithIndices(content), wraplinkAttrs) : content;
links.filter(function(i) {
return i.length > 15
}).forEach(function(i) {
post.content =
post.content.replace(i, function(m, k) {
console.log(i);
// return k === 2 ? m.slice(0,20) : m
return m.slice(0, 12)
})
})
var linkText = document.querySelector('.link_text');
linkText.innerHTML = post.content;
var short_link = linkText.cloneNode(true);
[].map.call(short_link.querySelectorAll('a'), function(i) {
i.innerText = i.innerText.slice(0, 10)
});
document.body.appendChild(short_link);
twitterText.extractUrls(String)返回匹配字符串所有url的数组 twitterText.autoLinkEntities 把url转成HTMLAnchorElement
这里截取用的是DOM接口,但考虑到后台可能会输出大量这样的含链接条目,在前端过多DOM操作不合适,假设后端是Node,如何只用ECMAScript实现链接文本截取效果
怪我咯2017-04-10 12:48:25
换了个思路解决 放弃使用 twitterText.autoLinkEntities,自己拼接生成HTML 后台代码
var postLinkTmpl= 'a(rel="nofollow",href=url,title=url,target="_blank") #{text}';
var sessionPost = {},
links = twitterText.extractUrls(content);
sessionPost.content = content;
links.forEach(function(i){
sessionPost.content =
sessionPost.content.replace(i,function(m){
return jade.compile(postLinkTmpl)({
url: m.match(/^http(s*):\/\//) ? m : 'http://' + m,
text: m.length > 20 ? m.slice(0,20) + '...' : m
})
})
})