基本上,我有一个未知数的字符串(由用户输入+我自己的数学确定),我需要将此字符串分成3部分。
例如,我可能有“ 1273498”。我需要将其拆分为两个字符,以及右侧的第3位和第4位,如下所示:
127
34
98
另一个示例:1234567890必须为:
123456
78
90
目前,我正在通过以下方式完成此操作:
// get first input box value
var depositgold = document.getElementById('v-gold').value;
// set it to 0 if it's empty
if(depositgold == null || depositgold == '')
depositgold = 0;
// second input box value
var depositsilver = document.getElementById('v-silver').value;
if(depositsilver == null || depositsilver == '')
depositsilver = 0;
// third input box value
var depositcopper = document.getElementById('v-copper').value;
if(depositcopper == null || depositcopper == '')
depositcopper = 0;
// combine the 3 input box values (adding dec to make split easier)
var depositnums = depositgold + '.' + depositsilver + depositcopper;
// do some math on our new value, then split it at out dec
var deposit12 = (0.15 * depositnums).toFixed(4).split(".");
// split the last part of the above split into 4 characters
var result12 = deposit12[1].split("", 3);
// keep the first part of out dec split
var deposit12gold = deposit12[0];
// combine the second part split results into paired numbers
var deposit12silver = result12[0] + result12[1];
var deposit12copper = result12[2] + result12[3];
// repeat the above process
var deposit24 = (0.30 * depositnums).toFixed(4).split(".");
var result24 = deposit24[1].split("", 3);
var deposit24gold = deposit24[0];
var deposit24silver = result24[0] + result24[1];
var deposit24copper = result24[2] + result24[3];
var deposit48 = (0.60 * depositnums).toFixed(4).split(".");
var result48 = deposit48[1].split("", 3);
var deposit48gold = deposit48[0];
var deposit48silver = result48[0] + result48[1];
var deposit48copper = result48[2] + result48[3];
我知道必须有一种更好(更理智)的方法来完成上述任务-我需要为该项目再做几次,而且我当然不希望继续这样做。
我是JS和编程的新手,所以请笑,不要试图笑得太厉害;)
最佳答案
尝试以下方法:
var str = "123412341";
var matches = str.match(/(.+?)?(.{2})?(.{2})?$/);
// matches[1] = 12341
// matches[2] = 23
// matches[3] = 41
您可能要根据输入内容修改RegEx,当前所有组都是可选的。