CoCoMo
CoCoMo

Reputation: 279

Javascript regular expression for creating HTML list

I have to create html list from this code

- ali
- hammad
- shah
-- haripur hazara
-- gaga goo
- naqvi

The '-' represents starting of a list and nested list elements have extra '-' symbol as you can see with 'haripur hazara' and 'gaga gogo'. There is no limit on how many nested lists one can insert. Any help will be greatly appreciated.

Thank you.

Upvotes: 0

Views: 181

Answers (1)

Tim Williams
Tim Williams

Reputation: 166685

var  h = [];
var d = 0, dl = 0;
var s = "- ali\n" +
        "- hammad\n" +
        "- shah\n" +
        "-- haripur  hazara\n" +
        "--- gaga goo\n" +
        "- naqvi ";

var a = s.split('\n'); 

for(var x=0,l=a.length;x<l;x++)
{
    d=a[x].indexOf(' ');
    if(d>dl){h.push('<ul>');}
    if(d<dl){h.push('</ul>');}
    h.push('<li>'+a[x].substring(d+1) + '</li>');
    dl=d;
}
while(d-- > 0){h.push('</ul>');}
document.getElementById('test').innerHTML = h.join('');

Upvotes: 1

Related Questions