有没有办法我们可以使用角度js对字符串进行子串,并在末尾添加省略号,而忽略锚标记,如果它进入子字符串?
例如,我的文字是:
Lorem Ipsum一直是业界的标准 自16世纪以来,当一个未知的打印机拿到一个虚拟文本 类型的厨房,并争先恐后地制作一本样本书。
我只能在省略号后显示最多70个字符的文字。
在这种情况下,从" 55 - 100约"是锚链接,子串从0,70中填充字符串并创建一个带有断链链接的坏字符串。
在HTML上,我正在使用:
> data-ng-bind-html
解析子字符串。
我们如何忽略字符串中的< a href="something.html" > < /a >
标签和其他内容的子字符串?
不想使用CSS,因为内容可以是任意长度。
使用的过滤器:
filter('customEllipsis', function() {
return function(input, number) {
if (input) {
return input.length > number ? input.substring(0, number) + '...' : input;
}
};
});
答案 0 :(得分:0)
您可以使用Angular的内置过滤器limitTo
答案 1 :(得分:0)
使用Angular sanitizer解析html。有关用法的示例,请参阅此jsbin。
app.filter('customEllipsis', function($sce) {
return function(input, number) {
if (input) {
input = input.length > number ? input.substring(0, number) + '...' : input;
input = $sce.trustAsHtml(input);
return input;
}
};
});
答案 2 :(得分:0)
以下是一个解决方案:
下面的代码段包含完整的实现。它以示例字符串
的示例结束
Click <a href="http://stackoverflow.com">this absolutely <b>ah-mah-zing</b> link</a> to access Stackoverflow.
限制分别为20个,25个,30个,35个,40个,45个和50个字符。
运行代码段以查看结果。
function limit(string, maxLength) {
let visit = function(node) {
if (count < maxLength) {
if (node.nodeType === Node.TEXT_NODE) {
let left = maxLength - count;
let length = node.nodeValue.length;
if (length > left) {
node.nodeValue = node.nodeValue.substring(0, left) + '...';
count += left;
} else {
count += length;
}
} else {
for (let childNode of Array.from(node.childNodes)) {
visit(childNode);
}
}
} else {
node.remove();
}
return node;
};
let dom = new DOMParser().parseFromString(string, "text/html");
let tree = dom.body;
let count = 0;
return visit(tree).innerHTML;
}
let string = 'Click <a href="http://stackoverflow.com">this absolutely <b>ah-mah-zing</b> link</a> to access Stackoverflow.';
document.getElementById('container').innerHTML = [20, 25, 30, 35, 40, 45, 50]
.map(maxLength => limit(string, maxLength))
.join('<br>');
<div id="container"></div>
<强>优点强>
<强>缺点强>
DOMParser
实例等)。