在 JavaScript 中使用 parseFloat() 或 parseInt() 和正则表达式(转换 CSV 文件)
Using parseFloat() or parseInt() and regex in JavaScript (converting a CSV file)
我正在将CSV文件转换为本地2D数组。 我想知道是否有更好的方法将字符串转换为 floats/int,而不是使用正则表达式,然后是 parseFloat()/parseInt。
想法/建议?
// numex() - checkes to see if the string (str) is a number
// returns number.valid (true||false) and number.value = (float||int||string)
numex = function(str){
number = {};
number.valid = false;
number.value = str;
// if we see a number then convert it to a floating point or integer
if((number.value.search(/[^0-9^'.^'$^'%^'-^'"^,^ ]+/) < 0) && str.length > 0) {
number.valid = true;
number.value = str.replace(/[^'-^0-9^'.]+/g, ''); // TODO add % coversion code for example if we see a 10% covert it to .1
if(number.value.search(/['.]/) >= 0) {
number.value = parseFloat(number.value); // replace floating point
} else {
number.value = parseInt(number.value); // replace integers
}
}
return number; // number.valid = true or false;
}
var num = numex("1.101");
alert(num.value);
我认为你根本不需要使用正则表达式。试试这个:
var num = {};
num.value = new Number(str);
num.valid = !isNaN(num.value);
数字构造函数比 parseInt 和 parseFloat 更严格,因为它不接受像 10aaa
或 1.2bbb
这样的字符串,因此不需要执行正则表达式检查。
我大大简化了代码,并使用了类似于LeZuse所做的东西。
isNaN(值) || 值 == "
https://github.com/designpro/jCSV
相关文章:
- 将po-box javascript正则表达式转换为c#regex
- 将 Javascript 正则表达式转换为 PHP
- 在 JavaScript 中使用 parseFloat() 或 parseInt() 和正则表达式(转换 CSV 文件)
- 将PHP中的正则表达式转换为javascript
- 将正则表达式转换为PHP
- 将 JavaScript 正则表达式转换为 asp.net vb
- 如何将 Php 正则表达式转换为 js
- 将 php 正则表达式转换为 javascript
- 如何将这个PHP正则表达式转换为JS
- 如何即时将字符串编码的 PHP 正则表达式转换为 JS 正则表达式
- 将正则表达式转换为在 JavaScript 中使用的表达式
- 使用正则表达式转换 JSON 密钥值
- 如何将 PCRE 正则表达式转换为 PHP
- 如何使用正则表达式转换多个字符
- 如何将此PHP正则表达式转换为Javascript正则表达式
- 将这个php正则表达式转换为javascript
- 将C#正则表达式转换为JavaScript正则表达式
- 将 js 正则表达式转换为 Python 正则表达式
- 将c#正则表达式转换为javascript
- 如何将JavaScript正则表达式转换为Java