jose
jose

Reputation: 1562

Split array to string list when one of the items in the array is a string with commas

To create a list in a dispayfield from an array, I use the following code that split the array items from the comma ',':

'fragrance_list': ["fragrance one" , "fragrance two", "fragrance seven"; 

 xtype: 'displayfield',
 name: 'fragrance_list',
 bind: '{record.fragrance_list}',
 renderer: function (value, field) {
 if (value && value.indexOf(',') > -1) {
    this.rndTpl = this.rndTpl || new Ext.XTemplate('<div style = "line-
 height: 150%;' +
        'margin-left: -25px; margin-top: -12px; padding-left: 5px; padding-
 right: 5px;">' +
        '<ul><li>{[values.fragrance_list.replace(/,/g, "<li/>")]}</li></ul>' 
         +
        '</div>');

   return this.rndTpl.apply({
      fragrance_list: value
   });

 } else {
    return '&nbsp' + value
 }
}

return something like:

. fragrance one
. fragrance two
. fragrance seven

The problem is when one of the array items, which may be in an indeterminate position of the array, has in its string one or more commas:

'fragrance_list': ["fragrance one" , "fragrance two", "fragrance A, n.º 5", "fragrance 7"; 

return

. fragrance one
. fragrance two
. fragrance A
. n.º 5
. fragrance 7

instead

. fragrance one
. fragrance two
. fragrance, n.º 5
. fragrance 7

Any ideas how to solve this?

Upvotes: 0

Views: 392

Answers (2)

Elad
Elad

Reputation: 2377

I'm not entirely sure about the structure of your code, but if it's a long string you want to cut, you can add the quotes themselves to the regex:

 '<ul><li>{[values.fragrance_list.replace(/" {0,}, {0,}"/g, "<li/>")]}</li></ul>'

So the regex will match:

  • single qute, (the /" part).
  • zero spaces or more (the ' {0,}' part).
  • single comma (the ',' part).
  • zero spaces or more (the ' {0,}' part).
  • single qute, (the "/ part).

But, if you trying to build a list by values in an array (even if it's an array with one element) then the right way is to do it with a map function:

arrOfData.map( function(dataUnit){
    renderString += "<li>" + dataUnit + "</li>";
});

Or in es6 syntax

arrOfData.map( dataUnit => renderString += `<li>${dataUnit}</li>`);

Upvotes: 3

shubham1js
shubham1js

Reputation: 280

>var frag= (fragrance_list.indexOf(' "," ') > -1)?fragrance_list.split('","'):fragrance_list;

for first& last:

 firstfrag=frag[0].split(' " ')[1];
 lastfrag=frag[frag.length-1].split(' " ')[0];

Upvotes: 0

Related Questions