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
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();