-4

I need to convert a string that looks like the following:

'* [-]Tree Item1',
'** [-]Tree Item1-1',
'*** Tree Item1-1-1',
'*** Tree Item1-1-2',
'*** Tree Item1-1-3',
'** Tree Item1-2',
'*** Tree Item1-2-1',
'** Tree Item1-3',
'* Tree Item2',
'** [-]Tree Item2-1',
'*** Tree Item2-1-1',
'**** Tree Item2-1-1-1',
'* Tree Item3'

into an HTML unordered list. Something like:

<ul>
   <li>
      Tree Item1
      <ul>
         <li>Tree Item1-1</li>
         ...
      <ul>
   </li>
   <li>
      Tree Item2
      <ul>
         <li>Tree Item2-1</li>
         ...
      <ul>
   </li>
   ...
</ul>

Any help appreciated.

PS: Markdown libraries are not an option for what I need to achieve. An algorithm that enables this to be done is what is required.

ClaraU
  • 877
  • 3
  • 11
  • 22

2 Answers2

0

Stack overflow uses PageDown, which will probably meet your needs.

Paul
  • 35,689
  • 11
  • 93
  • 122
0

A markdown library seemed a bit of an overkill and isn't really an option. I've been able to work out a solution that seems satisfactory for now...

Essentially, the markdown-like string is first split into an array. Then for each item in the array, depth and text information is calculated and this is used to build a nested array. Something like;

var arrList = str.split(','), //where str contains markdown-like string from question above 
    nestedArray = [];

Array.forEach(arrList, function (item) {
   var nodeData = this.getNodeDataFromString(item);                
   //build nested array based on level/text information returned for each item,
   nestedArray.push(someWorkedOutData(nodeData));
}

function getNodeDataFromString () {
   var matches = str.match(/\*/g),
        retVal = {
            level: matches.length - 1
        },
        regex;

    regex = new RegExp('^\\' + matches.join('\\') + ' (.*)');
    str.replace(regex, function (match, p1) {
        retVal.text = p1;
    });
    return retVal;
}

The nested array is then used to build the HTML markup via a recursive function.

Working solution here (I'm currently working with ExtJS so the solution is written using this library).

Comments/Critiques welcome.

Thanks,

C.

ClaraU
  • 877
  • 3
  • 11
  • 22