replace all comma seperated numbers to dot seperated numbers in string in javascript

Assume there are string with numbers, for instance, test() test 12,01% test (12,4) 12.3 s 2 some other text, other text, 2,text

I need to replace numbers with comma to the same numbers with dot and do not change anything else. So string would become

test() test 12.01% test (12.4) 12.3 s 2 some other text, other text, 2,text

I tried something like this:

var newstr = str.replace(/^\d+,\d+$/g, "\1.\2");

or var newstr = str.replace(^\d*\,?\d+$/g, "\1.\2");

  • I think this should match any number with comma: ^\d*\,?\d+$

Answers:

Answer

You could do it like this and capture 2 groups:

(\d+),(\d+)

Explanation

  • Group 1: capture 1 or more digits(\d+)
  • Match a comma ,
  • Group 2: capture 1 or more digits(\d+)

var str = "test() test 12,01% test (12,4)  12.3 s 2 some other text, other text, 2,text";
var newstr = str.replace(/(\d+),(\d+)/g, "$1.$2", ".");
console.log(newstr);

Answer
yourString.replace(/(\d),(\d)/g, "$1.$2")

This will match every comma between numbers.

Answer

Try this:

var newstr = str.replace( /\b(\d+),(\d+)\b/g, "$1.$2");

The purpose of having the \b word boundaries in there is to make sure that you don’t accidentally match numbers that are adjacent to letters. Since part of your example has the text 2,text, it appears that there is potential for some unusual text such as 2,1text to show up, in which case you probably don’t intend to replace the comma with a period.

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.