Javascript截断HTML文本
JavaScript是否有一种截断HTML文本的方法,而不必为匹配标记等而头疼Javascript截断HTML文本,javascript,html,truncate,Javascript,Html,Truncate,JavaScript是否有一种截断HTML文本的方法,而不必为匹配标记等而头疼 谢谢。没有内置的javascript。有一个你可以看一看的问题。这很有挑战性 如果您没有任何HTML标记,以下内容可能很有用 有一个mootools插件,它可以完全满足您的需要: 我最近刚刚完成了一个jQuery函数,它使用容器的宽度和高度来实现这一点。测试一下,看看它是否适合你。我还不确定所有的兼容性问题、bug或限制,但我已经在FF、Chrome和IE7中进行了测试 我也遇到了同样的问题,最后写了下面的
谢谢。没有内置的javascript。有一个你可以看一看的问题。这很有挑战性 如果您没有任何HTML标记,以下内容可能很有用
我最近刚刚完成了一个jQuery函数,它使用容器的宽度和高度来实现这一点。测试一下,看看它是否适合你。我还不确定所有的兼容性问题、bug或限制,但我已经在FF、Chrome和IE7中进行了测试
- 我也遇到了同样的问题,最后写了下面的文章来解决它。它将HTML截短到给定长度,清除可能在结尾处被剪掉的任何开始/结束标记,然后关闭所有未关闭的标记:
function truncateHTML(text, length) {
var truncated = text.substring(0, length);
// Remove line breaks and surrounding whitespace
truncated = truncated.replace(/(\r\n|\n|\r)/gm,"").trim();
// If the text ends with an incomplete start tag, trim it off
truncated = truncated.replace(/<(\w*)(?:(?:\s\w+(?:={0,1}(["']{0,1})\w*\2{0,1})))*$/g, '');
// If the text ends with a truncated end tag, fix it.
var truncatedEndTagExpr = /<\/((?:\w*))$/g;
var truncatedEndTagMatch = truncatedEndTagExpr.exec(truncated);
if (truncatedEndTagMatch != null) {
var truncatedEndTag = truncatedEndTagMatch[1];
// Check to see if there's an identifiable tag in the end tag
if (truncatedEndTag.length > 0) {
// If so, find the start tag, and close it
var startTagExpr = new RegExp(
"<(" + truncatedEndTag + "\\w?)(?:(?:\\s\\w+(?:=([\"\'])\\w*\\2)))*>");
var testString = truncated;
var startTagMatch = startTagExpr.exec(testString);
var startTag = null;
while (startTagMatch != null) {
startTag = startTagMatch[1];
testString = testString.replace(startTagExpr, '');
startTagMatch = startTagExpr.exec(testString);
}
if (startTag != null) {
truncated = truncated.replace(truncatedEndTagExpr, '</' + startTag + '>');
}
} else {
// Otherwise, cull off the broken end tag
truncated = truncated.replace(truncatedEndTagExpr, '');
}
}
// Now the tricky part. Reverse the text, and look for opening tags. For each opening tag,
// check to see that he closing tag before it is for that tag. If not, append a closing tag.
var testString = reverseHtml(truncated);
var reverseTagOpenExpr = /<(?:(["'])\w*\1=\w+ )*(\w*)>/;
var tagMatch = reverseTagOpenExpr.exec(testString);
while (tagMatch != null) {
var tag = tagMatch[0];
var tagName = tagMatch[2];
var startPos = tagMatch.index;
var endPos = startPos + tag.length;
var fragment = testString.substring(0, endPos);
// Test to see if an end tag is found in the fragment. If not, append one to the end
// of the truncated HTML, thus closing the last unclosed tag
if (!new RegExp("<" + tagName + "\/>").test(fragment)) {
truncated += '</' + reverseHtml(tagName) + '>';
}
// Get rid of the already tested fragment
testString = testString.replace(fragment, '');
// Get another tag to test
tagMatch = reverseTagOpenExpr.exec(testString);
}
return truncated;
}
function reverseHtml(str) {
var ph = String.fromCharCode(206);
var result = str.split('').reverse().join('');
while (result.indexOf('<') > -1) {
result = result.replace('<',ph);
}
while (result.indexOf('>') > -1) {
result = result.replace('>', '<');
}
while (result.indexOf(ph) > -1) {
result = result.replace(ph, '>');
}
return result;
}
函数truncateHTML(文本,长度){
var truncated=text.substring(0,长度);
//删除换行符和周围的空白
截断=截断。替换(/(\r\n |\n |\r)/gm“”).trim();
//如果文本以不完整的开始标记结尾,请将其修剪掉
truncated=truncated.replace(//我知道这个问题很老了,但我最近遇到了同样的问题。我编写了以下库,它可以安全地截断有效的HTML:如果你想在vanilla JS中找到一个轻量级的解决方案,这应该可以做到,尽管它会留下空元素,所以这取决于你是否关心这些元素。还要注意,它会在pla中变异节点行政长官
function truncateNode(node, limit) {
if (node.nodeType === Node.TEXT_NODE) {
node.textContent = node.textContent.substring(0, limit);
return limit - node.textContent.length;
}
node.childNodes.forEach((child) => {
limit = truncateNode(child, limit);
});
return limit;
}
const span=document.createElement('span');
span.innerHTML='foobarbaz';
截形烯醇(span,5);
expect(span.outerHTML).toEqual('fooba');
上述解决方案都与我的用例不完全对应,因此我自己创建了一个小型的香草javascript函数。它保留了空元素,但可以很容易地更正
const truncateWithHTML=(字符串,长度)=>{
//string=“我的长字符串,我想要短一点,但只需要一点”
const noHTML=string.replace(/]*>/g',);
//如果不需要截断字符串
if(noHTML.length)/g.filter(布尔值);
//substring=[,“我的长字符串,”,“我想要短一点,”,“但只是一点点,”]
让计数=0;
设截断=[];
for(设i=0;i 如果(!substr.startsWith("可悲的是,它充满了HTML标记,否则它就不会成为问题。我还没有使用过jQuery,它很容易实现,还是需要大量的设置和调整?jQuery插件链接被破坏了。这是我找到的唯一一个解决这个f*ing问题的健壮解决方案,应该要高得多。真不敢相信我第一次投了赞成票!太棒了@arendjr!npm i——为winit保存文本剪辑器打破了提供的HTML。测试方法:标题1
标题2 Titulo 3
OOOum texto modelo da indústria tipográfica e de impressúO.O Lorem Ipsum tem vindo a sero texto padrãO usado porúestrias des no 1500,quando uma misturou os《生活规范》中的文字特征。5年后的《生活规范》中的文字,以及《电气规范》中的《基本规范》中的文字
const span = document.createElement('span');
span.innerHTML = '<b>foo</b><i>bar</i><u>baz</u>';
truncateNode(span, 5);
expect(span.outerHTML).toEqual('<span><b>foo</b><i>ba</i><u></u></span>');