0

I'm making a postman call to an endpoint and i want to save in a variable only a number from my response body's field.

POST {{baseURL}}/{{version}}/{{customersEndpoint}}

response:
{
    "firstName": "te",
    "lastName": "test",
    "customerUrl": "/api/v1/customers/172"
}
var response = JSON.parse(responseBody)
console.log(response)
console.log(response.customerUrl)

I want to save in a variable only the number 172.

var customerID = response.customerUrl(something) ???

Thanks!

1
  • You could try parsing it, for example with a simple regex: response.customerUrl.match("\/[0-9]+")[0]. It gives "/172", actually, but you can modify it further yourself.
    – MasterAler
    Commented Apr 3, 2019 at 22:39

3 Answers 3

2

If this is representative of the expected format of customerUrl, you can do:

const customerUrlPieces = response.customerUrl.split('/');
const customerID = customerUrlPieces[customerUrlPieces.length - 1];
0
1

You could split the customerUrl string, and get just the number.

response= {
    "firstName": "te",
    "lastName": "test",
    "customerUrl": "/api/v1/customers/172"
}

const customerId = response.customerUrl.split("/")[4]

console.log(customerId)

1

you can get those numbers by matching them with a RegExp;

response.customerUrl.match(/\d{2,}/)[0]

\d{2,} will check for 2 or more digits in a row

1
  • Welcome to Stackoverflow, Robert, and thank you for your answer. Since this question already has a few other answers, it would be helpful if you can explain the benefit of your answer in relation to the other answers.
    – dovetalk
    Commented Apr 3, 2019 at 23:09

Not the answer you're looking for? Browse other questions tagged or ask your own question.