뭔가 일을 할 것입니다하지만 정규 표현식을 사용하지 않습니다 (하지만이 중 하나 jQuery를 사용하지 않습니다 그래서 2 명중 1 명은 나쁘지 않습니다.)
var s = '<span>A</span>BC<span id="blabla">D</span>EF';
function removeSpans(s) {
var a = document.createElement('div');
var b = a.cloneNode(true);
a.innerHTML = s;
var node;
while (a.firstChild) {
node = a.removeChild(a.firstChild);
if (node.tagName &&
node.tagName.toLowerCase() == 'span' &&
node.id == '') {
b.appendChild(document.createTextNode(getText(node)));
} else {
b.appendChild(node);
}
}
return b.innerHTML;
}
alert(removeSpans(s));
그것은 특히 강력한 없습니다 (사실은 내가 생각했던 것보다 더 잘 작동) 그리고 가능성이 테스트 케이스에 약간 다른 경우에 실패합니다. 그러나 그것은 전략을 보여줍니다. 여기
, 그래도 꽤 비슷한 다른 버전의 :
function removeSpans2(s) {
var a = document.createElement('div');
a.innerHTML = s;
var node, next = a.firstChild;
while (node = next) {
next = next.nextSibling
if (node.tagName && node.tagName.toLowerCase() == 'span' && !node.id) {
a.replaceChild(document.createTextNode(node.textContent || node.innerText), node);
}
}
return a.innerHTML;
}
당신이이 범위 밖에서의 확신 : [구문 분석하지 마십시오 (X) HTML 정규식 (http://stackoverflow.com/questions/ 1732348/regex-match-open-tags-except-xhtml-self-contained-tags # answer-1732454)? – fncomp
당신이 원하는 것이 있으며 어떤 것이 효과가 있습니다. 당신은 ** 정말로 ** 원하는가? 강력한 솔루션은 정규 표현식이 할 수없는 방식으로 문자열을 구문 분석해야합니다. – RobG
강력한 솔루션을 사용해도 괜찮습니다. 방금 정규식이 갈 길이라고 생각했습니다. –