skip to Main Content

I have list that I’m trying to split into an array.

The items in the list will not always follow the same pattern. Here’s the example list:

TestOne__Test One|1
TestTwo__Test Two|1
TestThree
TestFour__Test Four
TestFive|1

First I split each item by the ‘__’, which creates the parts array with parts[1] and parts[2] (for any lines that include the __

But, any list items that also contain the "|1" suffix, need to be split as well.

Ideally I will end up with a single parts arrays that looks like this (for each i):

parts = [TestOne, Test One, 1]
parts = [TestTwo, Test Two, 1]
parts = [TestThree, '', '']
parts = [TestFour, Test Four, '']
parts = [TestFive, '', 1]

Here’s the first split:

var promptList = ['TestOne__Test One|1', 'TestTwo__Test Two|1', 'TestThree', 'TestFour__Test Four'];
for (var i = 0; i < promptList.length; i++) {
    var parts = promptList[i].split('__');
}

I have tried splitting all at once with regex:

var parts = promptList[i].split(/__||/);

But that just jumbles up the array indexes. I want all the parts[0] items to be the First part of the line item, and parts[1] to be the second part of the line item (if there is one) and parts[2] to be the ‘1’ suffix (if there is one).

The syntax for each line is as follows:

*TestOne* = the data that is too be saved
*Test One* = the display text that is to be shown to the user if this value is exists, otherwise "TestOne" is shown
*1* = whether or not the value will be pre-selected

I’d like to be able to reference parts[2] and be sure that it’s referencing the ‘1’ value for each item. In the above list parts[1] for line 5 will be the ‘1’ value.

Thanks!

2

Answers


  1. Chosen as BEST ANSWER

    I think I found a solution.

    var promptList = ['TestOne__Test One|1', 'TestTwo__Test Two|1', 'TestThree', 'TestFour__Test Four', 'TestFive|1'];
    for (var i = 0; i < promptList.length; i++) {
      var parts = promptList[i].split(/__|[|]/);
      if (parts[1] == '1') {
         parts[2] = '1';
         parts[1] = undefined;
      }
    }
    

  2. You shouldn’t use a character class in your regular expression. The regular expression you want is /__||/ (or /__|[|]/ if you want to use the character class to escape the vertical bar) to match two underscores (or one vertical bar), not an underscore-or-apostrophe-or-vertical-bar.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search