给定代码行

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

and value = 9.61,我需要将9.61转换为9:61。如何使用JavaScript替换函数在这里?


这样做:

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);

更新到反映到当前版本的jQuery。这里也有很多答案最适合这种情况。作为开发人员,您需要知道哪个是哪个。

替换所有事件

要一次替换多个字符,可以使用如下的东西:name。替换(/ & / g,“-”)。这里我用-替换了所有&字符。G是全球的意思

注意-您可能需要添加方括号以避免错误-标题。替换(/[+]/g, " ")

归功于vissu和Dante Cullari


最优雅的方法可能是一步完成。看到瓦尔()。

$("#text").val(function(i, val) {
  return val.replace('.', ':');
});

相比:

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

从文档中可以看出:

.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.

这需要jQuery 1.4+。


(9.61 + "").replace('.',':')

或者如果你的9.61已经是一个字符串:

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

这可以用常规的JavaScript函数replace()来完成。

value.replace(".", ":");

我喜欢jQuery的方法链接。简单地做……

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

    //Or if you want to return the value:
    return $("#text").val().replace('.',':');

简单的一句话:

$("#text").val( $("#text").val().replace(".", ":") );

$("#text").val(function(i,v) { 
   return v.replace(".", ":"); 
});

你可以使用JavaScript函数,比如replace,你可以用括号括住jQuery代码:

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