2

I want to replace all points with comma:

var text = "1.2";
var comma = text.replace(/./g, ",");
console.log(comma);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

The result I expect:

1,2
peace_love
  • 6,229
  • 11
  • 69
  • 157
  • You have to escape the dot as this character has a special meaning in a regular expression: _"(The decimal point) matches any single character except the newline character"_ – Andreas Jan 26 '18 at 18:21
  • Possible duplicate of [How to replace all dots in a string using JavaScript](https://stackoverflow.com/questions/2390789/how-to-replace-all-dots-in-a-string-using-javascript) – Andreas Jan 26 '18 at 18:22

3 Answers3

3

You're using a regular expression (/./g) to find characters to replace; however, the period/dot (.) in regular expressions matches any-and-all characters (i.e it's a wildcard). This is why your output happens to be a string of just commas.

To get the behavior you're looking for (global search and replace of all periods), you must instead escape the dot with a backslash:

var text = "1.2.3";
var comma = text.replace(/\./g, ",");
console.log(comma); // => "1,2,3"
Ryan McGeary
  • 235,892
  • 13
  • 95
  • 104
1

Change /./g with this "."

var text = "1.2";
var comma = text.replace(".", ",");
console.log(comma);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Andam
  • 2,087
  • 1
  • 8
  • 21
  • I just wonder, why it is working the other way around: `text.replace(/,/g, ".")` If I want to replace comma with point – peace_love Jan 26 '18 at 18:22
  • @Jarla See my comment and/or the duplicate – Andreas Jan 26 '18 at 18:23
  • @Jarla . might have special meaning in regular expression. – Andam Jan 26 '18 at 18:23
  • Ah ok, I understand! – peace_love Jan 26 '18 at 18:31
  • This is not the appropriate answer, because it looks like @Jarla's intent is to do a global search and replace (not just replace the first match). See my answer for why your original attempt did not work and what you can do to remedy that. – Ryan McGeary Jan 26 '18 at 18:42
  • @Jarla That is correct. This will only replace the first dot it finds. If you have multiple dots in your string I suggest you use (Ryan) answer or (Commercial Suicide) answer – Andam Jan 26 '18 at 18:56
1

@Andam already answered about using replace method, and it's pretty cool for your case, but just good to know, that sometimes you can see the combination of split and join methods, which can be used for the same case:

var text = "1.2";
var comma = text.split(".").join(",");
console.log(comma);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

split method returns an array of pieces before and after the argument, passed to this method, so you can work with this array too, if needed. But as I already said, replace would be enough, if you just want to replace one character to another.

P.S.
  • 15,970
  • 14
  • 62
  • 86