Substring text with HTML tags in Javascript(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.
这篇关于Javascript中带有HTML标签的子字符串文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Javascript中带有HTML标签的子字符串文本


基础教程推荐
- 如何使用 CSS 显示和隐藏 div? 2022-01-01
- 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
- 如何在特定日期之前获取消息? 2022-01-01
- Node.js 有没有好的索引/搜索引擎? 2022-01-01
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
- 什么是不使用 jQuery 的经验技术原因? 2022-01-01
- WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
- 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
- 每次设置弹出窗口的焦点 2022-01-01
- Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01