0

How to explode string using javascript and regex after break <br> followed by one of the following tags enclosures </i> or </div> or </b> ?

For example if my string is:

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

or

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

or

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

The output of the string should be:

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

Thanks a lot!

hjuster
  • 3,985
  • 9
  • 34
  • 51

3 Answers3

1

This one should work :

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"]
0

The regexp you are looking for is this:

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

It uses positive lookahead (http://www.regular-expressions.info/lookaround.html) and non-capturing parenthesis.

Working example: http://jsbin.com/uGIxUZI/1/edit

PS: The examples in your question don't match your answer (< /br> instead of < br/>)

Tibos
  • 27,507
  • 4
  • 50
  • 64
0

To get only the text part, you can create a dummy element and add that text in to it. Something like this:

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);

Working Fiddle

Mr_Green
  • 40,727
  • 45
  • 159
  • 271
  • I have random number of nodes before I need to split the string. And i need to split it just on the first appearance, ideally with the split method. The final purpose is to make a handlebar helper... – hjuster Sep 18 '13 at 12:06
  • @hjuster So you want to split it only with the first occurence of the node. right? – Mr_Green Sep 18 '13 at 12:09