“替换不是功能" [英] "replace is not a function"
问题描述
我正在尝试从数字中删除逗号.
I'm trying to remove the comma from a number.
var thisbill_str = "";
thisbill = $('#linebill_' + z).val();
if (isNaN(thisbill) ) { thisbill = 0.00; }
thisbill_str = thisbill;
thisbill = thisbill_str.replace(/,/g, "");
这个 javascript 代码给了我一个错误:
This javascript code is giving me an error:
TypeError: thisbill_str.replace is not a function
如果我给它 'g' 和 'i' 标志并不重要.仅当字符串中尚未包含逗号时才执行此操作,即,如果字符串为 '515.00'.如果字符串是'5,515.00',那么它工作正常.我在文档中没有看到任何内容告诉我要替换的字符串必须实际存在.我错过了什么,有什么更好的方法可以做到这一点?
It doesn't matter if I give it the 'g' and 'i' flags. It only does it if the string does NOT already have a comma in it, i.e., if the string is '515.00'. If the string were '5,515.00', then it works fine. I don't see anything in the documentation that tells me that the string to be replaced has to actually exist. What am I missing, and what is a better way to do this?
推荐答案
很可能是因为 thisbill_str 不是字符串.也许您在某处有一些其他代码可以自动将 thisbill_str 转换为数字?
It is most likely caused by thisbill_str being something other than a String. Maybe you have some other code somewhere that automatically converts thisbill_str to a Number?
您可以使用 String(thisbill_str) 转换回字符串.
You can convert back to a string using String(thisbill_str).
完整的代码是:
thisbill = String(thisbill_str).replace(",", "")
这篇关于“替换不是功能"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!