5

たとえば、マークアップ付きの文字列があります (html ノードから):

こんにちはこれです

"h<em>e<strong>llo, thi</strong>s i</em><strong>s d</strong>og"

その中でいくつかの単語を見つけ (「こんにちは」と「犬」としましょう)、それらをスパンでラップし (ハイライトを作成)、すべてのマークアップを保存する最も正しい方法は何ですか?

望ましい出力は次のようなものです(タグが適切に閉じられていることに注意してください)

<span class="highlight">h<em>e<strong>llo</strong></em></span><strong>,</strong> <em><strong>thi</strong>s<em> i</em><strong>s <span class="highlight"><strong>d</strong>og</span>

見た目は同じです:

こんにちはこのです_ _ _

4

1 に答える 1

2

どうぞ:

//Actual string
var string = "h<em>e<strong>llo, thi</strong>s i</em><strong>s d</strong>og";

//RegExp to cleanup html markup
var tags_regexp = /<\/?[^>]+>/gi;

//Cleaned string from markup
var pure_string = string.replace(tags_regexp,"");

//potential words (with original markup)
var potential_words = string.split(" ");

//potential words (withOUT original markup)
var potential_pure_words = pure_string.split(" ");

//We're goin' into loop here to wrap some tags around desired words
for (var i in potential_words) {

    //Check words here
    if(potential_pure_words[i] == "hello," || potential_pure_words[i] == "dog")

    //Wrapping...
    potential_words[i] = "<span class=\"highlight\">" + potential_words[i] + "</span>";
}

//Make it string again
var result = potential_words.join(" ");

//Happy endings :D
console.log(result);
于 2012-06-04T19:13:32.343 に答える