An Chi Lê
An Chi Lê

Reputation: 19

Split characters in a string with a comma in javascript

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"

Upvotes: 1

Views: 1335

Answers (4)

KooiInc
KooiInc

Reputation: 122888

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)}`);

Upvotes: 0

41686d6564
41686d6564

Reputation: 19641

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

Upvotes: 0

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626689

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

Upvotes: 1

Vasily Liaskovsky
Vasily Liaskovsky

Reputation: 2528

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

Upvotes: 2

Related Questions