Учитывая, что синтаксический анализ html с регулярным выражением является плохой идеей , вот решение, которое делает именно это:)
РЕДАКТИРОВАТЬ: Просто чтобы прояснить: это не является допустимым решением, оно было задумано как упражнение, которое сделало очень мягкие предположения о входной строке, и как таковое должно быть принято с долей соли. Прочитайте ссылку выше и узнайте, почему анализ 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/
Примечание: решение Патрика Д. * может быть безопаснее в отношении плохого HTML, но я не уверен, насколько хорошо он обрабатывает пробелы.