How do I do string replace in JavaScript to convert ‘9.61’ to ‘9:61’?
Solution 1:
Do it like this:
var value = $("#text").val(); // value = 9.61 use $("#text").text() if you are not on select box...
value = value.replace(".", ":"); // value = 9:61
// can then use it as
$("#anothertext").val(value);
Updated to reflect to current version of jQuery. And also there are a lot of answers here that would best fit to any same situation as this. You, as a developer, need to know which is which.
Replace all occurrences
To replace multiple characters at a time use some thing like this: name.replace(/&/g, "-")
. Here I am replacing all &
chars with -
. g
means "global"
Note - you may need to add square brackets to avoid an error - title.replace(/[+]/g, " ")
credits vissu and Dante Cullari
Solution 2:
Probably the most elegant way of doing this is to do it in one step. See val()
.
$("#text").val(function(i, val) {
return val.replace('.', ':');
});
compared to:
var val = $("#text").val();
$("#text").val(val.replace('.', ':'));
From the docs:
.val( function(index, value) )
function(index, value)A function returning the value to set.
This method is typically used to set the values of form fields. For
<select multiple="multiple">
elements, multiple s can be selected by passing in an array.The
.val()
method allows us to set the value by passing in a function. As of jQuery 1.4, the function is passed two arguments, the current element's index and its current value:$('input:text.items').val(function(index, value) { return value + ' ' + this.className; });
This example appends the string " items" to the text inputs' values.
This requires jQuery 1.4+.