evan
evan

Reputation: 59

JavaScript: How do I capture particular value in a string?

I have the below strings and I need to capture the number 31 digit from the Mem: line. Spaces are dynamic so I am unable to capture the right number.

String:

Swap:            1          0          1        
Mem:            31         27          3          0          1         18

I am trying the below code and couldn't go further.

let lines = output.split('\n');
for (var i = 0; i < lines.length; i++) {
  var newArray = lines[i];

  if (newArray.indexOf('Mem:') > -1) {
    let n = newArray.split(":");

  }
}

Upvotes: 1

Views: 72

Answers (4)

Randy Casburn
Randy Casburn

Reputation: 14185

Provided with the 'Mem' string (presumably from your lines array) , it is this simple:

const str = "Mem:            31122       27          3          0          1         18";
const subStr = str.split(':')[1].trim();
const num = subStr.substr(0,subStr.indexOf(' '));

console.log(num);

If there are other constraints not ideified in the question I'll alter the answer as necessary.

Upvotes: 0

evan
evan

Reputation: 59

var lines = 'Swap:            1          0          1        \nMem:            31         27          3          0          1         18',
    firstNum = lines.split('\n').find(s => s.includes('Mem')).match(/\d+/);

console.log(firstNum[0]);

Upvotes: 0

adiga
adiga

Reputation: 35259

You could use the regex Mem:\s*(\d+) to get the first number after Mem: and unknown number of whitespaces to a capturing group. Then use match to get the capturing group which is at the index 1.

const str = `Swap:            1          0          1        
Mem:            31         27          3          0          1         18`

const [, number] = str.match(/Mem:\s*(\d+)/)

console.log(number)

Upvotes: 1

Nina Scholz
Nina Scholz

Reputation: 386881

You could find the line and get the first digits.

var lines = 'Swap:            1          0          1        \nMem:            31         27          3          0          1         18',
    firstNum = lines.split('\n').find(s => s.includes('Mem')).match(/\d+/);

console.log(firstNum[0]);

Upvotes: 0

Related Questions