简体   繁体   中英

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.

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM