How to count integers (only) in a phone number when the number contains special characters (like dashes)?

My question:
I have a phone number response of:

"phonenumber" : "805-555-5555"
or "phonenumber" : "(805) 555-5555"
or "phonenumber" : "8055555555"
or, well, you get the idea.

And I want to pm.expect for 10 integers, ignoring the special characters. The integer count is the test. The formatting varies. It can also be empty or null.

Details (like screenshots):

My current test fails because our API will return the phone exactly as passed to it in the request, special characters and all. They are not stripped out in the backend.

pm.test("Phone number is 10 numbers" + responsePhoneNumber.length, function () {
    pm.expect(responsePhoneNumber.length).to.eql(10);
});

I used to have a more relaxed test, but it was passing even when it was empty, so this is my current working copy.

1 Like

Regular expressions aren’t always the answer, but this seems like a good situation where it will cleanly/easily do what you want.

responsePhoneNumber.replace(/\D/g,"")

This will take all non-numeric characters (\D) and replace them with an empty character, meaning that only numbers will be left. (It will also preserve nulls and empty strings, where they already exist)

1 Like

This works, thanks! I’m using a postman data file to swap the different possibilities out.

A limitation to this solution is that if you put this before another test, the value it’s checking will still be 8055555555 unless you reset it after. I moved my test that compares input and output, so that it is hit before this test and that solves for it. Warranted a note, though, so someone who comes after me doesn’t reorganize it and think their test is just dandy.

Final solution:

// Run other tests before this one. Changes how responsePhoneNumber is formatted.
pm.test("Phone number is 10 numbers" + responsePhoneNumber.length, function () {
    responsePhoneNumber = responsePhoneNumber.replace(/\D/g,"");
    console.log(jsonData.contactdetails + " cleans up to " + responsePhoneNumber)
    pm.expect(responsePhoneNumber.length).to.eql(10);
    });
1 Like

Glad to hear it worked! :tada:

If you don’t want to tightly couple the ordering of your tests, there’s no reason why you have to give the cleaned-up version the same name; for instance -

cleanedPhoneNumber = responsePhoneNumber.replace(/\D/g,"");
pm.expect(cleanedPhoneNumber.length).to.eql(10);

Now if you reference responsePhoneNumber after this test, it will still be the original value with special characters.

1 Like