0

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.

3 Answers3

1

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));
NullPointer
  • 7,094
  • 5
  • 27
  • 41
0

If your string pattern is always the same, you can use the Regular expressions like this:

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

if (/\d+\sFIXED BUT(\s|\w+|\d+)+(\n\r)/g.test(a)) {

    var result = /((\d+\s)(FIXED BUT)(\s|\w+|\d+)+(\n\r))/g.exec(a);
    console.log("this is result: " + result[0]);
}

/*this is result: 7 FIXED BUT FX KFY 200

9 FIXED BUT FZ MX KFY 150 KMZ 200*/
Pouria Parhami
  • 182
  • 1
  • 2
  • 13
0

If you don't want to end with an array of string but with a string your can use String.slice as below:

var data = "20 FIXED\r\n7 FIXED BUT FX KFY 200\r\n9 FIXED BUT FZ MX KFY 150 KMZ 200\r\nLOAD 1 LOADTYPE Dead  TITLE DEAD";
var innerData = data.slice(data.indexOf('\r\n') + 2, data.lastIndexOf('\r\n'));
console.log(innerData);
Aris2World
  • 1,214
  • 12
  • 22