TwoRE
TwoRE

Reputation: 57

JQuery / Javascript & Split within split?

A Caveat: As a dilettante I lack the vocabulary to precisely describe my problem. Bear with me.

Let's assume I have a string like the following one:

A1%%A2%%A3%%A4||B1%%B2%%B3%%B4||C1%%C2%%C3%%C4||D1%%D2%%D3%%D4

Using JavaScript / JQuery I would like to split it twice (using '||' and '%%' as delimiters) and have the following HTML as output:

<p><input value="A1"></input><input value="A2"></input><input value="A3"></input><input value="A4"></input></p>
<p><input value="B1"></input><input value="B2"></input><input value="B3"></input><input value="B4"></input></p>
<p><input value="C1"></input><input value="C2"></input><input value="C3"></input><input value="C4"></input></p>
<p><input value="D1"></input><input value="D2"></input><input value="D3"></input><input value="D4"></input></p>

I know how to do basic splitting and joining, but this goes beyond my comprehension.

Upvotes: 1

Views: 100

Answers (3)

Quentin Engles
Quentin Engles

Reputation: 2832

All split joins. It will be fast.

var str = 'A1%%A2%%A3%%A4||B1%%B2%%B3%%B4||C1%%C2%%C3%%C4||D1%%D2%%D3%%D4',
    result = str.split('||').join('"></input></p>\n<p><input value="');

result = '<p><input value="'+
        result.split('%%').join('"></input><input value="')+
        '"></input></p>';

console.log(result);
//or
//alert(result);
//

With problems like this don't think so much about what format you want. Start with something simple first like:

var result = str.split('||').join('><');
result = str.split('%%').join('><');

Then you might see how to use the longer string to get what you actually want.

Upvotes: 1

Lesha Ogonkov
Lesha Ogonkov

Reputation: 1238

You can use replace

function splitString(match, part) {
  switch (part) {
    case '%%':
      return '"></input><input value="';
          
    case '||':
      return '"></input></p>\n<p><input value="';
  }
}

var formattedValue = 'A1%%A2%%A3%%A4||B1%%B2%%B3%%B4||C1%%C2%%C3%%C4||D1%%D2%%D3%%D4'.replace(/(%%|\|\|)/g, splitString);

formattedValue = '<p><input value="' + formattedValue + '"></input></p>';

console.log(formattedValue);

Upvotes: 1

Omidam81
Omidam81

Reputation: 1917

You can use something like this.

s = "A1%%A2%%A3%%A4||B1%%B2%%B3%%B4||C1%%C2%%C3%%C4||D1%%D2%%D3%%D4"; 
s2 = s.split("||");  
s2.forEach(function(item){ 
  s3 = item.split("%%"); 
  s3.forEach(function(item2){ 
       console.log(item2); 
  }); 
});

Upvotes: 1

Related Questions