Javascript中带有HTML标签的子字符串文本
您有解决方案在 Javascript 中使用 HTML 标记对文本进行子字符串处理吗?
Do you have solution to substring text with HTML tags in Javascript?
例如:
var str = 'Lorem ipsum <a href="#">dolor <strong>sit</strong> amet</a>, consectetur adipiscing elit.'
html_substr(str, 20)
// return Lorem ipsum <a href="#">dolor <strong>si</strong></a>
html_substr(str, 30)
// return Lorem ipsum <a href="#">dolor <strong>sit</strong> amet</a>, co
推荐答案
考虑到 用正则表达式解析 html 是个坏主意,这是一个解决方案:)
Taking into consideration that parsing html with regex is a bad idea, here is a solution that does just that :)
要明确一点:这不是一个有效的解决方案,它的目的是对输入字符串做出非常宽松的假设,因此应该谨慎对待.阅读上面的链接,看看为什么永远无法使用正则表达式解析 html.
function htmlSubstring(s, n) {
var m, r = /<([^>s]*)[^>]*>/g,
stack = [],
lasti = 0,
result = '';
//for each tag, while we don't have enough characters
while ((m = r.exec(s)) && n) {
//get the text substring between the last tag and this one
var temp = s.substring(lasti, m.index).substr(0, n);
//append to the result and count the number of characters added
result += temp;
n -= temp.length;
lasti = r.lastIndex;
if (n) {
result += m[0];
if (m[1].indexOf('/') === 0) {
//if this is a closing tag, than pop the stack (does not account for bad html)
stack.pop();
} else if (m[1].lastIndexOf('/') !== m[1].length - 1) {
//if this is not a self closing tag than push it in the stack
stack.push(m[1]);
}
}
}
//add the remainder of the string, if needed (there are no more tags in here)
result += s.substr(lasti, n);
//fix the unclosed tags
while (stack.length) {
result += '</' + stack.pop() + '>';
}
return result;
}
示例: http://jsfiddle.net/danmana/5mNNU/
注意:patrick dw 的解决方案可能是对坏 html 更安全,但我不确定它处理空格的效果如何.
Note: patrick dw's solution may be safer regarding bad html, but I'm not sure how well it handles white spaces.
相关文章