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标签的子字符串文本
- Flexslider 箭头未正确显示 2022-01-01
- 400或500级别的HTTP响应 2022-01-01
- 失败的 Canvas 360 jquery 插件 2022-01-01
- Fetch API 如何获取响应体? 2022-01-01
- 使用RSelum从网站(报纸档案)中抓取多个网页 2022-09-06
- Quasar 2+Apollo:错误:找不到ID为默认的Apollo客户端。如果您在组件设置之外,请使用ProvideApolloClient() 2022-01-01
- CSS媒体查询(最大高度)不起作用,但为什么? 2022-01-01
- Css:将嵌套元素定位在父元素边界之外一点 2022-09-07
- addEventListener 在 IE 11 中不起作用 2022-01-01
- 如何使用 JSON 格式的 jQuery AJAX 从 .cfm 页面输出查 2022-01-01