0

javascript と regex を使用して文字列を分解する方法 ブレーク<br>の後に次のタグのいずれかが続く エンクロージャ</i>または</div>または</b>?

たとえば、私の文字列が次の場合:

var string = "Some text<div><br></div>Second part of the text";

また

var string = "Some text<b><br></b>Second part of the text";

また

var string = "Some text<i><br></i>Second part of the text";

文字列の出力は次のようになります。

string[0] = "Some text";
string[1] = "Second part of the text";

どうもありがとう!

4

3 に答える 3

1

これはうまくいくはずです:

var r = /<i><br><\/i>|<b><br><\/b>|<div><br><\/div>/;
var s = "Some text<i><br></i>Second part of the text";
s.split(r); // ["Some text", "Second part of the text"]
于 2013-09-18T12:16:33.783 に答える
0

テキスト部分のみを取得するには、ダミー要素を作成してそのテキストを追加します。このようなもの:

function getText(txt) {   
    var main = document.getElementById('main');  //can also be "document"
    var div = document.createElement('div');     //dummy element
    div.innerHTML = txt;
    main.appendChild(div);
    var c = div.childNodes;
    var arr = [];
    for (var i = 0; i < c.length; i++) {
        if (c[i].nodeType == 3) {         //condition to filter the text nodes
            arr.push(c[i].data);
        }
    }
    main.removeChild(div);             //remove dummy element
    return arr;                        //return array
}

var str = getText("Some text<div></br></div>Second part of the text");
console.dir(str);

働くフィドル

于 2013-09-18T12:03:45.300 に答える
0

あなたが探している正規表現はこれです:

/<br\/>(?=(?:(?:<\/b>)|(?:<\/i>)|(?:<\/div>)))/

正の先読み ( http://www.regular-expressions.info/lookaround.html ) と非キャプチャ括弧を使用します。

作業例: http://jsbin.com/uGIxUZI/1/edit

PS: あなたの質問の例はあなたの答えと一致しません (< br/> の代わりに < /br>)

于 2013-09-18T11:57:11.910 に答える