Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to get a comma separation between numbers in an array?

I am having beginners trouble with comma separation from numbers extracted using regular expressions. The exercise is as follows:

Find and print all the digits from the sentence as a single array. If the sentence has no digits, print "No digits!". Try to do the check using the test()-method.

This is my result: Screenshot of the code and result

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

var sentence = "5om3 wr173 w0rd5 u51n9 numb3r5"

function printDigits() {
  var res = sentence.replace(/\D/g, '');
  console.log(res)
}

printDigits();

>Solution :

You could spread the final number to get an array, then use join() to add those comma’s. (join uses , as the default separator

As a fallback, you can use OR || to set the value of res to a string you like

var sentence = "5om3 wr173 w0rd5 u51n9 numb3r5"

function printDigits() {
    var res = [ ...sentence.replace(/\D/g, '') ].join() || "No digits!";
    console.log(res)
}

printDigits();
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading