我当前正在使用replace在四个字符字符串(1000(的 第二个字符工作代码const myStr = "1000";
const string = myStr.replace(/(d{2})(d{2})/g, '$1:$2');
console.log(string);
您仍然可以使用一个适用于任何时间长度的正则表达式,比如四个或六个数字,每组两个带有冒号。
const
format = s => s.replace(/.(?=(..)+$)/g, '$&:');
console.log(format('1000'));
console.log(format('100000'));
保持简单。使用字符串函数操作字符串:
const s1 = "1000";
const s2 = s1.slice(0, 2) + ":" + s1.slice(2);
console.log(s2);
这绝对不是最好的方法,我只是想知道有多少替代品
[...'1000'].map((c, i) => i !== 0 && i % 2 === 0 ? `:${c}` : c).join('') //10:00
[...'100000'].map((c, i) => i !== 0 && i % 2 === 0 ? `:${c}` : c).join('') //10:00:00
[...'10000000'].map((c, i) => i !== 0 && i % 2 === 0 ? `:${c}` : c).join('') //10:00:00:00
您可以使用模板文字:
const x = "1000"
const result = `${x.slice(0, 2)}:${x.slice(2)}`
console.log(result)
你可以尝试一个子字符串,比如这个
var mystring = '1000';
var method1 = mystring.substring(0, 2) + ':' + mystring.substr(2);
console.log(method1);
你可以制作你自己的功能
String.prototype.insert = function(index, string) {
if (index > 0){
return this.substring(0, index) + string + this.substr(index);
}
return string + this;
};
var mystring='1000';
var method2=mystring.insert(2,':');
console.log(method2);