Search code examples
javascriptstringlinefeed

Skip the same string value


var data = "20 FIXED\r\n7 FIXED BUT FX KFY 200\r\n 9 FIXED BUT FZ MX KFY 150 KMZ 200\r\nLOAD 1 LOADTYPE Dead  TITLE DEAD";


function pullBetTwoStrings(data, str1, str2) {

 return data.split(str1)[1].split(str2)[0].trim();
}

var support_FBnode_data = pullBetTwoStrings(data, "FIXED", "LOAD" );
console.log(pullBetTwoStrings(data,"FIXED", "LOAD"));

I have a list of string in this kind of format:

var data = "20 FIXED\r\n
           7 FIXED BUT FX KFY 200\r\n
           9 FIXED BUT FZ MX KFY 150 KMZ 200\r\n
           LOAD 1 LOADTYPE Dead  TITLE DEAD"

How do i get the middle ones only? I want to achieve like this:

7 FIXED BUT FX KFY 200
9 FIXED BUT FZ MX KFY 150 KMZ 200

I have a code below that i use in order to get the in between data but it stops whenever it reaches the FIXED string again.

function pullBetTwoStrings(data, str1, str2) {

 return data.split(str1)[1].split(str2)[0].trim();
}

var support_FBnode_data = pullBetTwoStrings(data, "FIXED", "LOAD" );

so the above codes give me the result of 7 cause it is in between of Two FIXED strings.


Solution

  • Below are the steps to achieve this:

    Step 1.Convert string data to array by splitting with \r\n.

    Step 2. Use array.shift(); This removes the first element from an array and returns only that element.

    Step 3. Use array.pop(); This Removes the last element from an array and returns only that element.

    var data = "20 FIXED\r\n7 FIXED BUT FX KFY 200\r\n 9 FIXED BUT FZ MX KFY 150 KMZ 200\r\nLOAD 1 LOADTYPE Dead  TITLE DEAD";
    
    
    function pullBetTwoStrings(data) {
         var result=data.split("\r\n");
         result.shift();
          result.pop(); 
         return result;
    }
    
    console.log(pullBetTwoStrings(data));