Explain Codes LogoExplain Codes Logo

How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?

javascript
string-manipulation
regex
javascript-utility-methods
Nikita BarsukovbyNikita Barsukov·Nov 8, 2024
TLDR

Simple as a mocha latte! You apply the replace() method, a special power of JavaScript strings:

'9.61'.replace('.', ':');

It finds the first . in '9.61' and replaces it with :, giving you a cool '9:61'.

Exploring the replace() method's superpowers

Diving into what replace() does below the surface, it's essentially a string superhero, capable of both simplicity and mighty functionalities. However, it has a weakness — it only takes out the first . in a given string.

Tweak the superpower with a Global Regular Expression to conquer this vulnerability. The g flag tells JavaScript to replace all the villains (dots):

'9.61.30'.replace(/\./g, ':'); // Bam, '9.61.30' becomes '9:61:30'.

Dealing with special characters and jQuery val()

Regular expressions can be tricky when they include special characters, but we aren't afraid. We can simply put these characters in square brackets, which is like a protective suit for them. Check it out:

'9.61.30'.replace(/[.]/g, ':'); // Boss level passed.

Meanwhile, when playing with jQuery and interacting with the DOM, we use the val() method to engage with input element values:

// Set the new value $('#timeInput').val('9.61').val(function(i, val) { return val.replace(/[.]/g, ':'); }); // Check out the new value, voila! console.log($('#timeInput').val());

Unless you're working with non-form input elements — in that case, text() would be your sidekick.

Code reuse and robust function building

Hate repeating yourself? Me too! A function is like your own JavaScriptronic reusable capsule. You write the logic once, encapsulate it in a function, and call it whenever you need it. Time efficient, isn't it?

function replaceDotsWithColons(input) { return input.replace(/[.]/g, ':'); } console.log(replaceDotsWithColons('9.61')); // Console: 'Haha, I got '9:61'!'

Now call this function with different inputs, and enjoy functional time manipulation.

String-to-number conversions

We occasionally bump into strings that look like numbers. To perform calculations or comparisons, we must convert these strings to number types:

const timeString = '9.61'; const timeNumber = Number(timeString.replace('.', ':'));

Please remember, replacing a . with : in a string is like trying to swim after turning water into sand. It doesn't work with mathematical operations!

jQuery version compatibility and method chaining

Working with jQuery requires vigilance. You need a version that supports your arsenal. Using .val() with a function argument, for example, calls for jQuery 1.4 or above. And method chaining? Well, that's just showing off your jQuery efficiency.

Handling immutable strings

JavaScript strings are immutable, bummer! This means whatever operations you perform on them, they don’t alter the original string. They give you a new string instead. So, remember to store the result of a replace() operation in a new variable:

const originalTime = '9.61'; const updatedTime = originalTime.replace('.', ':'); // JavaScript: 'Nah, I ain't gonna change the original.'

Multiple test cases

Beauty of JavaScript? It makes testing a breeze. Create various walking scenarios (maybe even dancing ones?) for your outputs to ensure their reliable performance.