我想将字符串子串起来,如下所示.我有字符串的起始位置和长度.我在Javascript中用HTML标签检查了这个问题的子串文本.但是在这个子串中从0开始执行,但我有一个随机的起始位置.关于它将如何完成的任何想法
var str = 'Lorem ipsum <p>dolor <strong>sit</strong> amet</p>, consectetur adipiscing elit.'
Run Code Online (Sandbox Code Playgroud)
这是DEMO
function html_substr( str, start ,count ) {
var div = document.createElement('div');
div.innerHTML = str;
walk( div, track );
function track( el ) {
if( count > 0 ) {
var len = el.data.length;
if(start<=len){
el.data = el.substringData(start,len);
start=0;
} else{
start-=len;
el.data = '';
}
len = el.data.length;
count -= len;
if( count <= 0 ) {
el.data = el.substringData( 0, el.data.length + count );
}
} else {
el.data = '';
}
}
function walk( el, fn ) {
var node = el.firstChild;
do {
if( node.nodeType === 3 ) {
fn(node);
} else if( node.nodeType === 1 && node.childNodes && node.childNodes[0] ) {
walk( node, fn );
}
} while( node = node.nextSibling );
}
return div.innerHTML;
}
Run Code Online (Sandbox Code Playgroud)
称之为
html_substr( str,13, 2 );
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1882 次 |
| 最近记录: |