How can I add a comma to separate each group of th

2019-06-16 07:03发布

I have a text input field for a form where users are meant to enter a number. I would like to automatically insert a comma after every third digit.

For example, entering '20' would result in '20'. Entering '100' would result in '100'. But if they were to enter '1000', a comma would be inserted between the 1 and the following 0's (e.g., 1,000). Obviously this behaviour would continue should the number reach 7 digits (e.g., 1,000,000).

Is there an easy way to do this? I'm a bit of a newb at all of this, so please answer like you're talking to a child :)

10条回答
Lonely孤独者°
2楼-- · 2019-06-16 08:05

Yes, it's not terribly difficult. I believe this reference may give you what you need.

Note that for this to be dynamic (as they type) you'd need to have this wired to the input field change handler. Otherwise, you can wire this to the input field blur handler (which will have the effect of putting the commas in the field when they leave the field).

查看更多
虎瘦雄心在
3楼-- · 2019-06-16 08:06
function addCommas(nStr){
    var offset = nStr.length % 3;
    if (offset == 0)
        return nStr.substring(0, offset) + nStr.substring(offset).replace(/([0-9]{3})(?=[0-9]+)/g, "$1,");
    else
        return nStr.substring(0, offset) + nStr.substring(offset).replace(/([0-9]{3})/g, ",$1");
}


alert(addCommas("1234567"));
查看更多
ゆ 、 Hurt°
4楼-- · 2019-06-16 08:07

The following javascript:

function format(input)
{
    var nStr = input.value + '';
    nStr = nStr.replace( /\,/g, "");
    var x = nStr.split( '.' );
    var x1 = x[0];
    var x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while ( rgx.test(x1) ) {
        x1 = x1.replace( rgx, '$1' + ',' + '$2' );
    }
    input.value = x1 + x2;
}

and the following HTML:

<input type="text" onkeyup="format(this)">

should solve your problem. The key is to use 'onkeyup'.

Try it here http://jsfiddle.net/YUSph/

查看更多
smile是对你的礼貌
5楼-- · 2019-06-16 08:09

for the fun of it:

'9876543210'
    .split('') // flip the entire string so that we can break every
    .reverse() //   3rd digit, starting from the end
    .join('')
    .split(/(...)/) // split on every 3rd
    .reverse()      // flip the string again, though now each group of 3 is
    .join(',')      //   backwards
    .replace(/,(?=,)|,$|^,/g, '') // remove extra ,
    .replace(/(,|^)(\d)(\d)?(\d)?/g, '$1$4$3$2') // flip each group of digits
// 9,876,543,210

Anyone want to take a stab at making that better?

查看更多
登录 后发表回答