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
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
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"
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 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.