Organizational Research By

Surprising Reserch Topic

how do i do string replace in javascript to convert 9 61 to 961


how do i do string replace in javascript to convert 9 61 to 961  using -'javascript,jquery'

Given the code line

var value = $("#text").val();


and value = 9.61, I need to convert 9.61 to 9:61. How can I use the JavaScript replace function here?
    

asked Sep 22, 2015 by rolvyrf
0 votes
7 views



Related Hot Questions

3 Answers

0 votes

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, needs to know which is which..

answered Sep 22, 2015 by virendra.bajaj
0 votes

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

0 votes

I love jQuery's method chaining. Simply do...

    var value = $("#text").val().replace('.',':');

    //Or if you want to return the value:
    return $("#text").val().replace('.',':');
answered Sep 22, 2015 by r3tt

...