I’m currently trying to parse out a 6-digit verification code that is being sent in an API request’s response body along with some text.
For example:
GET -> https://api.twilio/com/...
The response body returns something like this:
"body": "Your code is 123456."
I’m parsing via JSONpath ($.messages[0].body
) and saving that string ("Your code is {number}") as a variable.
I’m trying to figure out how to then take that saved variable and parse out just the set of numbers from the string.
I’ve done a lot of stuff, but this is all new to me and I’m learning as I go.
3
Answers
You can extract the value ‘123456’ from the given JSON object by using a regular expression like so:
You can use regex to extract the number:
$.messages[0].body.match(/(d+)/)[1]
If you know the structure of the response will always be consistent, you can use
str.splice()
to get the specific answer and useNumber()
to make it a number data type. So if the response is like what you said and you’ve saved the answer to a variable calledresponseStr
. You can doSince it is always a 6-digit code, the start index (13) and end index of the code (18) will remain the same. The second parameter should be end index + 1 since the splice is exclusive of the index of the second parameter.
However, if the response may have a different structure but you are sure the code is always a 6-digit verification code, you can use REGEX to find the string and convert it to a number data type. So something like
where
/[0-9]{6}/g
is the regex for 6-digit number. But you’ll need to make sure it is the only number of 6-digit or more in the response ormatchArr
will contain all the combination of substrings that is a 6-digit number or you will need to modify the REGEX to create a more specific match.