简体   繁体   English

如何在javascript中的n位数之后拆分数字?

[英]How to split a number after n digits in javascript?

I have a number 2802 which is stored as a string in the backend. 我有一个数字2802,它在后端存储为一个字符串。 I want to split this number into 2 parts as 28 and 02 which should be shown as date 28/02? 我想将这个数字分成两部分,28和02,应该显示为28/02日期? How can I do it with '/' in between them? 我怎么能用它们之间的'/'来做?

Try this : you can use substring as shown below. 试试这个:你可以使用substring ,如下所示。 substring used for getting string between start index and end index. substring用于获取起始索引和结束索引之间的字符串。 In your case, get string from 0 to 1 and then 2 to 3. 在您的情况下,从0到1然后从2到3获取字符串。

 var str = "2802"; str = str.substring(0,2) + "/" + str.substring(2,4); alert(str); 

More information on Substring 有关Substring的更多信息

Solution with regex 解决方案与正则表达式

 var res = "2802".match(/\\d{2}/g).join('/'); document.write(res); 

Are you asking about simple string manipulation? 你在问简单的字符串操作吗?

var str = "1234";
var res = str.substr(0, 2)+"/"+str.substr(2,4);

You can do this: 你可以这样做:

 var str = "2802"; str = str.split('').map(function(el, i){ if(i == 2){ el = '/'+el} return el; }); document.querySelector('pre').innerHTML = str.join(''); 
 <pre></pre> 

With regular expression: 使用正则表达式:

 var str = "2802"; str = str.replace(/(.{1,2}$)/gi, '/$1'); document.querySelector('pre').innerHTML = str; 
 <pre></pre> 

var str = "2802";
var output = [str.slice(0, 2), str.slice(2)].join('/');

In this context conside 2802, 28 is date and 02 is month 在这种情况下,考虑2802,28是日期,02是月

Here 112 , 028 what is date and month ? 这里112,028是什么日期和月份?

A more generic solution could be 一个更通用的解决方案可能是

var num = 2802;
var output = String(num).match(new RegExp('.{1,2}', 'g')).join("/");

replace 2 with which ever number to split the number after n digits. 将n替换为2号以分割n位数后的数字。

var n = 2;
var output = String(num).match(new RegExp('.{1,'+n+'}', 'g'));
var db_date = '112';
var date_str = '';
if(db_date.slice(0,1)==0){
    var date_val = db_date.slice(0,2);
    var month_val = db_date.slice(2,3);

    if(month_val<=9){
        month_val = '0'+month_val;
    }
}else{
    var date_val = db_date.slice(0,1);
    date_val = parseInt(date_val);
    if(date_val<=9){
        date_val = date_val.toString();
        date_val = '0'+date_val;
    }
    var month_val = db_date.slice(1,3);
}
alert(date_val+'/'+month_val);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM