1

I'm trying to write a regex function that return all of the digits in a comma separated string:

function printDigits() {
   var result = sentence.replace(/[^0-9]/g, '').split(",")
    console.log(result)
}

But it just prints out a string instead of digits being separated by comma. Are there any ways I can fix this?

Input: "5om3 wr173 w0rd5 u51n9 numb3r5."

Expected output: "5,3,1,7,3,0,5,5,1,9,3,5"

2
  • Please provide sample input and output Commented Jul 25, 2021 at 8:49
  • sentence.match(/\d/g)? sentence.match(/\d/g).join(",")? Commented Jul 25, 2021 at 8:52

4 Answers 4

2

split doesn't work this way. It splits by the separator that is already in the input. To split string to individual characters use split(''), and then join individual characters with comma:

   var result = sentence.replace(/[^0-9]/g, '').split('').join(',');
Sign up to request clarification or add additional context in comments.

Comments

1

You can use

sentence.match(/\d/g).join(",")

Here,

  • sentence.match(/\d/g) - extracts each separate digit from string
  • .join(",") - join the array items into a single comma-delimited string.

See the JavaScript demo:

var sentence = "5om3 wr173 w0rd5 u51n9 numb3r5.";
console.log(sentence.match(/\d/g).join(","));
// -> 5,3,1,7,3,0,5,5,1,9,3,5

Comments

0

Here's another variation that uses pure regex and does not require a .join() call:

sentence.replace(/\D+|(\d)(?=\d)/g, '$1,');

This replaces any string of non-digit characters with a comma. And it also locates the position between two digits and adds a comma between them.

Pattern breakdown:

  • \D+ - Match one or more non-digit characters.
  • | - OR...
  • (\d) - Match one digit and capture it in group 1.
  • (?=\d) - Followed by another digit.
  • Substition:
    • $1, - Replace with whatever was captured in group 1, plus a comma.

Here's a full demo:

var sentence = "5om3 wr173 w0rd5 u51n9 numb3r5";
var result = sentence.replace(/\D+|(\d)(?=\d)/g, '$1,');
console.log(result); // 5,3,1,7,3,0,5,5,1,9,3,5

Comments

0

A reducer solution

const x = `5om3 wr173 w0rd5 u51n9 numb3r5`
  .split('')
  .reduce((acc, val) =>
    val.trim().length && !isNaN(+val) ? [...acc, +val] : acc, []);
console.log(`${x}`);

Or simply

console.log(`${`5om3 wr173 w0rd5 u51n9 numb3r5`.match(/\d/g)}`);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.