3

HTML コンテンツの検索強調表示に JavaScript RegExp を使用しています。

そのために私は使用しています:

data.replace( new RegExp("("+search+")", 'g'), "<b id='searchHighlight'>$1</b>" );

ここdataで、 は HTML コンテンツ全体で、searchは検索文字列です。

たとえば、 を検索すると、h単語 (the、there など) の h が強調表示され、タグ内のインスタンスも強調表示されます"<h1 id="title"> Something </h1>"

同じスタイルで同じ HTML コンテンツを強調表示する必要があるため、別のアプローチをとることはできません。

私は次のような解決策を読みました:

var input = "a dog <span class='something'> had a  </span> and a cat";
// Remove anything tag-like
var temp = input.replace(/<.+?>/g, "");
// Perform the search
var matches = new RegExp(exp, "g").exec(temp);

しかし、同じ HTML コンテンツ内の検索テキストを強調表示する必要があるため、既存のタグを単純に取り除くことはできません。たとえば、次のように破損し ないようh「the」で強調表示できるように、RegExpで検索を含めて除外する方法はありますか?"t<b id='searchHighlight'>h</b>e"
"<h1 id="title">Test</h1>""<<b id='searchHighlight'>h</b>1 id="title">Test</<b id='searchHighlight'>h</b>1>"

HTML コンテンツは静的で、次のようになります。

    <h1 id="title">Samples</h1>
        <div id="content">
            <div  class="principle">
        <h2 id="heading">           
            PRINCIPLE</h2>


        <p>
            FDA recognizes that samples are an important part of ensuring that the right drugs are provided to the right patients. Under the Prescription Drug Marketing Act (PDMA), a sales representative is permitted to provide prescription drug samples to eligible healthcare professionals (HCPs). In order for BMS to provide this service, representatives must strictly abide by all applicable compliance standards pertaining to the distribution of samples.</p></div>
<h2 id="heading">           
            WHY DOES IT MATTER?</h2>
        <p>
            The Office of Inspector General (OIG) recognizes that samples can have monetary value to HCPs and, when used improperly, may have implications under the Federal False Claims Act and the Federal Anti-kickback Act. To minimize risk of such liability, the OIG requires the clear and conspicuous labeling of individual samples as units that cannot be sold.&nbsp; BMS and its business partners label every sample package to meet this requirement.&nbsp; Additionally, the HCP signature statement acknowledges that the samples will not be sold, billed or provided to family members or friends.</p>
        <h2 id="heading">

            WHO IS YOUR SMaRT PARTNER?</h2>
        <p>
            SMaRT is an acronym for &ldquo;Samples Management and Representatives Together&rdquo;.&nbsp; A SMaRT Partner has a thorough understanding of BMS sample requirements and is available to assist the field with any day-to-day policy or procedure questions related to sample activity. A SMaRT Partner will also:</p>

        <ul>
            <li style="margin-left:22pt;"> Monitor your adherence to BMS&rsquo;s sample requirements.</li>
            <li style="margin-left:22pt;"> Act as a conduit for sharing sample compliance issues and best practices.</li>
            <li style="margin-left:22pt;"> Respond to day-to-day sample accountability questions within two business days of receipt.</li>
        </ul>
        <p>

            Your SMaRT Partner can be reached at 888-475-2328, Option 3.</p>
        <h2 id="heading">

            BMS SAMPLE ACCOUNTABILITY POLICIES &amp; PROCEDURES</h2>
        <p>
            It is the responsibility of each sales representative to read, understand and follow the BMS Field Sample Accountability Procedures, USPSM-SOP-101. The basic expectations are:</p>
        <ul>
            <li style="margin-left:22pt;"> Transmit all sample activity by communicating your tablet to the host server on a <strong>daily</strong> basis.</li>
            <li style="margin-left:22pt;"> Maintain a four to six week inventory of samples rather than excessive, larger inventories that are more difficult to manage and increase your risk of non-compliance.</li>
            <li style="margin-left:22pt;"> Witness all HCP&rsquo;s signatures to confirm request and receipt of samples.</li>
        </ul>
</div>

コンテンツはすべて散らばっており、1 つのタグだけではありません。したがって、DOM 操作は私にとって解決策ではありません。

4

3 に答える 3

4

タグの属性にまたはがないと確信できる場合は、単に使用<できます>

data = data.replace( 
    new RegExp( "(" + search + "(?![^<>]*>))", 'g' ),
        "<b id='searchHighlight'>$1</b>" );

負の先読みは、タグ内の場合と同様に、文字列内の先読みの前に(?![^<>]*>)ある場合、置換を防ぎます。><

これは絶対確実というわけではありませんが、これで十分かもしれません。

ところで、グローバルに一致しているため、つまり複数の置換を行っているため、id='searchHighlight'おそらくclass='searchHighlight'.

searchまた、正規表現の特殊文字が含まれていないことに注意する必要があります。

于 2013-03-13T15:18:28.287 に答える
1

おそらく、仕事に間違ったツールを使用しようとしているという事実を認識しているので、これは単なる記録用です (そうでない場合は、これが洞察に満ちていることに気付くかもしれません)。

title基本的に任意のテキスト コンテンツを含む html 属性、つまり(ツールチップ属性) とdata-...(設計により任意のデータを保持するための一般的なユーザー定義属性)で 1 つの基本的な問題に遭遇する可能性があります (おそらくそうなりますか?)。あなたのhtmlコード、あなたもそこに見つけることができます.バルーンヘルプを汚したり、いくつかのアプリケーションロジックを壊したりする置換. また、テキスト コンテンツの任意の文字が、名前付きまたは数値エンティティ (例: &-> &amp;&#x26;&#38;) としてエンコードされる可能性があることにも注意してください。これは、原則として処理できますが、動的正規表現が複雑になります (変数searchがストレート テキストを保持する場合に非常に大きくなります)。

以上のことをすべて言ったので、強調表示される検索結果に正規表現仕様のセマンティクスを持つ文字が含まれていない限りうまくいくかもしれません。これらは適切にエスケープする必要があります。data.replace( new RegExp("([>]?)[^><]*("+search+")[^><]*([<]?)", 'g'), "<b id='searchHighlight'>$1$2$3</b>" );.+*|([{}])\-

要約すると、多くのトラブルからあなたを救うためにあなたのデザインを修正してください

ところで、dom traversal を選択しないのはなぜですか? そのために存在する実際の html タグについて知る必要はありません。

于 2013-03-13T14:49:18.157 に答える
0

これは純粋な RegExp ソリューションではありませんが、DOM をトラバースできない場合は、このような機能的な置換とループを使用した文字列操作がうまくいく可能性があります。

  1. 必要な変数を宣言し、ドキュメント本文の innerHTML をフェッチします。
  2. データを調べて、タグを抽出し、それらを配列に保存します。後で元に戻す場所がわかるように、プレースホルダーを残します。
  3. 文字列内のすべてのタグを一時的なプレースホルダーに置き換えたら、元のコードを使用して必要な文字を置き換えることができますが、結果をdata.
  4. 次に、以前のプロセスを逆にしてタグを復元する必要があります。
  5. dataドキュメント本文の innerHTML としてnew を割り当てます。

これが実行中のプロセスです。

コードは次のとおりです。

var data = document.body.innerHTML, // get the DOM as a string
    tagarray = [], // a place to temporarily store all your tags
    tagmatch = /<[^>]+>/g, // for matching tags
    tagplaceholder = '<>', // could be anything but should not match the RegExp above, and not be the same as the search string below
    search = 'h'; // for example; but this could be set dynamically

while (tagmatch.test(data)) {
    data = data.replace(tagmatch, function (str) {
        tagarray.push(str); // store each matched tag in your array
        return tagplaceholder; // whatever your placeholder should be
    });
}

data = data.replace( new RegExp("("+search+")", 'g'), "<b id='searchHighlight'>$1</b>" ); // now search and replace the string of your choice

while (new RegExp(tagplaceholder, 'g').test(data)) {
    data = data.replace(tagplaceholder, function (str) {
        return tagarray.shift(str); // replace the placeholders with the tags you saved earlier to restore them
    });
}

document.body.innerHTML = data; // assign the changed `data` string to the body

明らかに、これをすべて独自の関数に入れることができれば、上記のようなグローバル変数をぶらぶらさせたくないので、はるかに優れています。

于 2013-03-13T15:09:04.400 に答える