我想在Dom树中获得最后一个“可见”角色,然后将Dom分割到这个级别。
分割前的样本:
<div class="myclass"><label>mon label</label><span class="spanclass"></span></div>
^---- last visible character
分割后的样本:
<div class="myclass"><label>mon labe</label></div>
<div class="myclass"><label>l</label><span class="spanclass"></span></div>
Doe有谁知道怎么做?
我的代码:
function reverseString(str)
{
return (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0);
}
var domString = ' <div class="myclass"><label>mon label</label><span class="spanclass"></span></div>'; //' ';
var domSpace = domString.replace(/ +/g, ' ');
var revDom = reverseString(domSpace);
var re = /((\>[^\<\/]+\/?\<)+)*(\s+|\;[a-zA-Z#0-9]+\&|(\>\/[a-zA-Z]+\<)+|[^\>])/i;
var found = revDom.match(re);
var str1 = domSpace.substr(0, domSpace.length - found[0].length);
var str2 = domSpace.substr(domSpace.length - found[0].length, found[0].length);
console.log(str1 + ' ------- ' + str2);
由于
答案 0 :(得分:0)
这是你如何获得最后一个角色:
var p = document.getElementsByClassName("myclass")[0];
var data = p.children[0].innerHTML
var lastChar = data[data.length -1];
然后您可以通过执行以下操作来替换它:
p.children[0].innerHTML = lastChar;
答案 1 :(得分:0)
这是我的解决方案:
function reverseString(str)
{
return (str === '') ? '' : reverseString(str.substr(1)) + str.charAt(0);
}
function removeClosed(str)
{
var tothreat = str;
re = /<(\w+)[^>]*>[^<]*<\/(\w+)>/gi;
while (tothreat.match(re))
{
var tothreat = tothreat.replace(re, function(str, p1, p2, offset, s) {
if (p1 === p2) return '';
return str;
});
}
return tothreat;
}
var domString = '<div class="myclass"><label>mon label</label><span class="spanclass"></span></div>';
var domSpace = domString.replace(/ +/g, ' ');
var revDom = reverseString(domSpace);
var re = /((>[^<\/]+\/?<)+)*(\s+|\;[a-zA-Z#0-9]+\&|(>\/[a-zA-Z]+<)+|[^>])/gi;
var found = revDom.match(re);
var str1 = domSpace.substr(0, domSpace.length - found[0].length);
var str2 = domSpace.substr(domSpace.length - found[0].length, found[0].length);
var str = removeClosed(str1);
str = str.replace(/<\w+\/>/gi, '');
str = str.replace(/>[^<]+</gi, '><');
found = str.match(/(<\w+[^>]*>)+/gi);
var part2 = found[0] + str2;
str = removeClosed(str2);
found = str.match(/(<\/\w+>)*/gi);
var part1 = str1 + found[1];
console.log(part1)
console.log(part2);