最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Split a number with regex on the decimal point or end of string. - Stack Overflow

programmeradmin1浏览0评论

Here is an example of what I want to happen

50.1->['50','.1']
50 ->['50','']

I have tried using .split or .match. I got it to work with decimals, but not without.

'51.11'.split(/(?=\.)/);//works
'51'.split(/(?=\.)|$/);//doesn't

I'm aware I could do this in several steps, but I thought it might be possible with regex. I am trying to learn regex, but the pipe character does not behave as I expect it to. Also, I am not sure if this is even possible.

Here is an example of what I want to happen

50.1->['50','.1']
50 ->['50','']

I have tried using .split or .match. I got it to work with decimals, but not without.

'51.11'.split(/(?=\.)/);//works
'51'.split(/(?=\.)|$/);//doesn't

I'm aware I could do this in several steps, but I thought it might be possible with regex. I am trying to learn regex, but the pipe character does not behave as I expect it to. Also, I am not sure if this is even possible.

Share Improve this question asked Jul 30, 2011 at 4:33 qw3nqw3n 6,3346 gold badges34 silver badges63 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 4

You could just use match with /(\d+)(\.\d+)?/:

m = "50".match(/(\d+)(\.\d+)?/)
# ["50", "50", undefined]

m = "50.4".match(/(\d+)(\.\d+)?/)
# ["50.4", "50", ".4"]

The m[1] and m[2] values are populated with the capture groups.

If you really need a space, you could try something like /(\d+)((?:\.?)\d*)?/:

m = "50.0".match(/(\d+)((?:\.?)\d*)?/)
# ["50.0", "50", ".0"]

m = "50.".match(/(\d+)((?:\.?)\d*)?/)
# ["50.", "50", "."]

m = "50".match(/(\d+)((?:\.?)\d*)?/)
# ["50", "50", ""]

But then you'd have to check for "." instead of checking for undefined. You could start adding more groups and alternations to take care of the single "." problem but I don't see how that would be any better than:

first  = m[1];
second = m[2] || '';

Use .match with /(\d+)((?:\.\d+)?)/.

/(\d+)(\.\d+|)/ would also work. The second group will match either a dot and 1 or more digits, or an empty string.

The | is the alternative operator. /\.|$/ matches either a '.' or $, which stands for the end of the string. The reason putting the $ in the regex doesn't result in an empty string in the array is because split never puts the thing you split the string on into the array. You'll notice that the decimal point is "missing" as well.

I laugh sometimes at the lengths that people will go solve a problem with a regex when a few lines of regular non-regex code are sometimes much more readable, easier to control the exact result and probably an order of magnitude faster.

Here's a non regex way to produce a two element array, where the first element of the array has the left part of the number and the second element of the array has the decimal part of the number and is always preceded with a period.

jsFiddle here: http://jsfiddle/jfriend00/vTPrv/.

Code:

var testStrings = [
    "50",
    "50.",
    "50.4",
    "0.4",
    ".4",
    "0",
    "50.4444"
];

function getDecimalPieces(str) {
    if (str[0] == ".") {
        str = "0" + str;   // make sure we always have first part
    }
    var pieces = str.split(".");
    if (pieces.length == 1) {
        pieces.push("0");   // add decimal part
    }
    if (pieces[1] == "") {
        pieces[1] = "0";
    }
    if (pieces.length > 2) {
        pieces.slice(2);    // remove any extra pieces
    }
    pieces[1] = "." + pieces[1];   // add period back onto decimal piece
    return(pieces);
}

for (var i = 0; i < testStrings.length; i++) {
    var result = getDecimalPieces(testStrings[i]);
    $("#result").append("[" + result[0] + ", " + result[1] + "]<br />");
} 

Results:

[50, .0]
[50, .0]
[50, .4]
[0, .4]
[0, .4]
[0, .0]
[50, .4444]
发布评论

评论列表(0)

  1. 暂无评论