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();
4
Answers
You can get comma separation by converting the string to an array and then joining seperated by commas with the join method
You could
spread
the final number to get anarray
, then usejoin()
to add those comma’s. (join uses,
as the default separatorAs a fallback, you can use OR
||
to set the value ofres
to a string you likeIf you follow the question’s prompt to use
test()
this becomes a matter of testing each character, rather than manipulating the string.In long hand you can iterate over the string itself, here using a for…of loop
This can be shortened somewhat using spread syntax to convert the string to an array and then the array
filter()
method to only keep those characters that pass thetest()
.Instead of
replacing
characters usematch
which returns an array based on a regex pattern. You can even pass in an argument specifying if you want to return an array of strings or numbers.