SpartaSixZero
SpartaSixZero

Reputation: 2421

How to replace every dot in string with a "/" in JavaScript

Say I have a date string in the form of "11.23.13" and I want to replace every dot with a "/" so it looks like "11/23/13".

Here's my code but it's not working correctly because regular expression sees the "." and interprets that as matching every single character instead of new lines. So instead of "11/23/13", I get "////////".

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>RegExMatchDot</title>
    <script type="text/javascript">
        var myDate = "11.23.13";
        var myDateWithNewSeparator = myDate.replace(new RegExp(".", "g"), "/");
        console.log("my date with new date separator is: ", myDateWithNewSeparator);
    </script>
</head>
<body>

</body>
</html>

Anyone know a way around this issue? Thanks!

Upvotes: 2

Views: 1760

Answers (2)

kkemple
kkemple

Reputation: 992

a fast way to do replaces like this without the regex is to use split and join, so it would be:

myDate.split('.').join('/');

Believe it or not this used to be faster than replace but it is not anymore, anyway I would learn regex but for tiny replaces this is quite sufficient.

Upvotes: 2

adeneo
adeneo

Reputation: 318182

You can target all the periods with a regex that uses the global modifier, just remember to escape the period as periods have special meaning in a regex (as you've experienced, they match any character) :

var myDate = "11.23.13";
var myDateWithNewSeparator = myDate.replace(/\./g, '/');

Upvotes: 4

Related Questions