-1

A user can type In a separated list In an input field like this for example:

123, 123, 123

123!123!123

123:123:123

When the use Is finished, I want to replace all non-numeric characters with a comma-sign. How can I do that? When the user Is finished, I want the string to be separated with comma signs

I have tried like this:

var accidentFieldVal = $('#accidentId').val().split(/[ ,]+/).join(',');
accidentFieldVal = accidentFieldVal.replace(/,\s*$/, "");
Rory McCrossan
  • 331,213
  • 40
  • 305
  • 339
Bryan
  • 3,421
  • 8
  • 37
  • 77
  • 2
    Can you give an example of your expected output, and the JS code you've written to attempt to solve this – Rory McCrossan Jan 22 '16 at 09:14
  • @RoryMcCrossan: Expected output? The expected output should be the string with comma signs instead. Check the updated code with my attempt. – Bryan Jan 22 '16 at 09:16
  • 2
    Comma signs instead of... what? `I want to replace all the characters with a comma-sign` would imply you're trying to get `,,,,,,,,,,,` but I'm assuming that's not right. – Rory McCrossan Jan 22 '16 at 09:17
  • @RoryMcCrossan: Check my question? "I want to replace all the characters with a comma sign".... Charachters, not the numbers. The !, :, and blank space – Bryan Jan 22 '16 at 09:19
  • Right, now it makes sense. 'All characters' includes the numbers and symbols, hence why it wasn't clear. I edited your question to include that. – Rory McCrossan Jan 22 '16 at 09:20
  • Possible duplicate of [strip non-numeric characters from string](http://stackoverflow.com/questions/1862130/strip-non-numeric-characters-from-string) – Pete Jan 22 '16 at 09:24

4 Answers4

2

If you're after a simple way to replace groups of non-digits with commas, the following will suffice:

function replaceWithCommas (data) {
    return data.replace(/[^\d]+/g, ",");
}

[^\d]+ simply matches one or more non-numeric character.

Running:

console.log (replaceWithCommas("123, 123, 123"));
console.log (replaceWithCommas("123!123!123"));
console.log (replaceWithCommas("123:123:123"));

Outputs:

123,123,123
123,123,123
123,123,123
Adrian Wragg
  • 7,311
  • 3
  • 26
  • 50
1
Try this

var str = "123! 22! 33"; 
var res = str.replace(/[^\d]+/g, ",");
Jobelle
  • 2,717
  • 1
  • 15
  • 26
0

try this:

accidentFieldVal = $('#accidentId').val();
accidentFieldVal = accidentFieldVal .replace(/^[^\d]+|[^\d]+$/g, '');
accidentFieldVal = accidentFieldVal .replace(/[^\d]+/g, ',');
Vegeta
  • 1,319
  • 7
  • 17
0

Shriya R s answer is for integers only. If you want to use double values too, try this:

var target = "10:20:30:40.0";

function replaceComma(str)
{
   return str.replace(/[^\d.]+/g, ',');
}

replaceComma(target); // output: "10,20,30,40.0"