How To Replace A Comma With A Dot In JavaScript

Replace a comma with a Dot in JavaScript

To replace a comma with a Dot in JavaScript. We have tested effectively with two methods using the replace() methods and using the split() and join() methods. Check out the details below to get more information.

Replace a comma with a Dot in JavaScript

Using the replace() method

The best simple way to replace a comma with a dot is using the replace() method. This method allows you to use the regular expression to find out the comma in your string and replace it with a dot. We already have an article on how to use this method. Please read it here

Example:

In this example, we will use replace() method with the g modifier set to loop to all strings and replace all commas with a dot. g in the regular expression is for global search. Please view the code example below to get more information.

var myString = "Hello, I'm LearnShareIT,,,";
 
// use regular expression with replace() method with g modifier
newString = myString.replace(/,/g, '.')
 
console.log(newString)

Output

Hello. I'm LearnShareIT...

Using the split() and join() methods

The other way to replace a comma with a dot is by using the split() method to split a string into an array of substrings and then using the join() methods. Join the value of the string in the list and replace commas with a dot separator. The Join() and split() methods are ES1 features. It is fully supported for all browsers.

Split() method

Syntax: string.split(separator, limit)

Parameters: 

  • separator: a string or regular expression to use for splitting.
  • limit: an integer that limits the number of splits. Items after the limits are excluded.

Return value: return value is an array containing the split values.

Join() method

Syntax: string.join(iterable)

Parameters: 

  • iterable: any iterable object where all the returned values are strings. Default is a comma

Return value: return value is a string that must be specified as the separator.

Example:

In this example, we will use the split() method to split the string on commas into a list, and then we re-join all elements and replace them with a Dot. See the code example below to understand.

var myString = "Hello, I'm LearnShareIT,,,";
 
// splitting the string on comma by using split() method 
parts = myString.split(',');
 
// and re-join all with Dot
newString = parts.join('.');
console.log(newString)

Output

Hello. I'm LearnShareIT...

Summary

In this tutorial, we have explained how to replace a comma with a Dot in JavaScript by using two methods. We always hope this tutorial is helpful to you. Leave your comment here if you have any questions or comments to improve the article. Thanks for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *