2

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!

1
  • You have to escape the period character in the regexp. new RegExp("\\.", "g") Commented Nov 23, 2013 at 21:21

2 Answers 2

4

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, '/');
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.