2013-05-04 16 views
5

kullanarak saklayın. Bu benim dizemdir.Cümleleri HTML içeren dizgeye dönüştürün ve ayrıca ayırıcıyı Javascript

First sentence. Here is a <a href="http://google.com">Google</a> link in the second sentence! The third sentence might contain an image like this <img src="http://link.to.image.com/hello.png" /> and ends with !? The last sentence looks like <b>this</b>??

Ben cümleler dize (dizi) bölmek istediğiniz HTML yanı sıra ayırıcı tutmak: Bazı HTML içeriyor. Bunun gibi:

[0] = First sentence. 
[1] = Here is a <a href="http://google.com">Google</a> link in the second sentence! 
[2] = The third sentence might contain an image like this <img src="http://link.to.image.com/hello.png" /> and ends with !? 
[3] = The last sentence looks like <b>this</b>?? 

Bunu yapmanın bir yolu var mı? Regex kullanıyor ve eşleşiyor olabilir mi?

Bu HTML bit ile çok Peşinde olduğum şey yakın, ama gerçekten geçerli: JavaScript Split Regular Expression keep the delimiter

+1

Sanırım html'iniz yuvalanmış olabilir, bu bir span içeren bir p içerir. O zaman onu ayrıştırmaktan başka bir çözümün yok. –

+1

Etiket içeriğinin içinde "cümle ayırıcıları" varsa ne olur? –

+0

Ve ayırıcınız nedir? '. 'ya da'? 'ya da'! 'ya da' ?? ' veya yukarıdakilerin tümü ... – CoR

cevap

1

kolay kısmı ayrıştırma olduğu; dizenin etrafına bir eleman sarmak suretiyle bunu kolayca yapabilirsiniz. Cümleleri bölmek biraz daha karmaşıktır; Bu ona ilk bıçak geçerli:

var s = 'First sentence. Here is a <a href="http://google.com">Google.</a> link in the second sentence! The third sentence might contain an image like this <img src="http://link.to.image.com/hello.png" /> and ends with !? The last sentence looks like <b>this</b>??'; 

var wrapper = document.createElement('div'); 
wrapper.innerHTML = s; 

var sentences = [], 
buffer = [], 
re = /[^.!?]+[.!?]+/g; 

[].forEach.call(wrapper.childNodes, function(node) { 
    if (node.nodeType == 1) { 
    buffer.push(node.outerHTML); // save html 
    } else if (node.nodeType == 3) { 
    var str = node.textContent; // shift sentences 
    while ((match = re.exec(str)) !== null) { 
     sentences.push(buffer.join('') + match); 
     buffer = []; 
     str = str.substr(re.lastIndex + 1); 
     re.lastIndex = 0; // reset regexp 
    } 
    buffer.push(str); 
    } 
}); 

if (buffer.length) { 
    sentences.push(buffer.join('')); 
} 

console.log(sentences); 

Demo

tam cümle bulunana kadar bir element ya da bitmemiş cümle ya bir tampon olarak eklenen bulunuyor Her düğüm; Daha sonra sonuç dizisine eklenir.

+0

Bunun için teşekkür ederim. Ne yazık ki bazen başarısız oluyor. Lütfen bu örneğe bir göz atın: http://jsbin.com/acoyiv/2 – suprb

+0

@suprb Her cümle bulunduğunda RegExp nesnesini sıfırlamayı unuttum; şimdi sabit olmalı :) –

+0

Çok teşekkür ederim Jack. Harika çalışıyor. ;) – suprb

İlgili konular