HTML子字符串处理是指在HTML文档或字符串中提取、操作特定部分的内容。这涉及到DOM操作、字符串处理和安全考量。
// 从元素中获取文本子字符串
function getTextSubstring(element, start, length) {
const text = element.textContent || element.innerText;
return text.substr(start, length);
}
// 使用示例
const div = document.getElementById('myDiv');
const substring = getTextSubstring(div, 0, 10);
console.log(substring);
// 获取元素的HTML子字符串
function getHtmlSubstring(element, start, length) {
const html = element.innerHTML;
return html.substr(start, length);
}
// 使用示例
const htmlSubstring = getHtmlSubstring(div, 0, 50);
console.log(htmlSubstring);
直接操作innerHTML可能存在XSS风险,建议对输入进行净化:
function sanitizeHtml(html) {
const temp = document.createElement('div');
temp.textContent = html;
return temp.innerHTML;
}
// 获取文本子字符串
function getJQueryTextSubstring(selector, start, length) {
return $(selector).text().substr(start, length);
}
// 获取HTML子字符串
function getJQueryHtmlSubstring(selector, start, length) {
return $(selector).html().substr(start, length);
}
// 使用示例
const textSub = getJQueryTextSubstring('#myDiv', 0, 10);
const htmlSub = getJQueryHtmlSubstring('#myDiv', 0, 50);
// 替换元素中的部分文本
function replaceTextSubstring(selector, start, length, newText) {
const $el = $(selector);
const text = $el.text();
$el.text(text.substr(0, start) + newText + text.substr(start + length));
}
// 使用示例
replaceTextSubstring('#myDiv', 5, 3, 'NEW');
原因:直接在HTML字符串上使用substring/substr会破坏标签完整性。
解决方案:
// 安全截取HTML内容,保持标签完整
function safeHtmlSubstring(html, maxLength) {
let result = '';
let tagStack = [];
let length = 0;
let i = 0;
while (i < html.length && length < maxLength) {
if (html[i] === '<') {
// 处理标签
const tagEnd = html.indexOf('>', i);
if (tagEnd === -1) break;
const tag = html.substring(i, tagEnd + 1);
result += tag;
if (tag[1] !== '/') {
// 开始标签
tagStack.push(tag);
} else {
// 结束标签
tagStack.pop();
}
i = tagEnd + 1;
} else {
result += html[i];
length++;
i++;
}
}
// 补全未闭合的标签
while (tagStack.length > 0) {
const tag = tagStack.pop();
const tagName = tag.match(/<\s*(\w+)/)[1];
result += `</${tagName}>`;
}
return result;
}
原因:频繁的DOM操作或大字符串处理会导致性能问题。
解决方案:
// 使用文档片段处理大量内容
function processLargeContent(content) {
const fragment = document.createDocumentFragment();
const tempDiv = document.createElement('div');
tempDiv.innerHTML = content;
while (tempDiv.firstChild) {
fragment.appendChild(tempDiv.firstChild);
}
return fragment;
}
没有搜到相关的文章