Recently encountered a requirement to pass in a string, insert a space every three characters
Cases:
Incoming abcd1234
Output ABC D12 34
Think for a moment, ready to write a function as follows
Copy Code code as follows:
function Appendspace (s)
{
var length = s.length;
var result = "";
var last = 0;
for (var i = 3;i<=length;i=i+3,last = last+3)
{
result = Result+s.substring (i-3,i) + "";
}
result = Result+s.substring (last,length);
return result;
}
Feel this function is a bit of a dick silk ...
and replaced the Replace () regular expression substitution method
Copy Code code as follows:
/*
*$1 represents the first pair of parentheses in a reference matching rule (here is "(. { 3}) "") Hits the text
* Direct output when no parenthesis is added
*/
function Insertspace (s)
{
var result =s.replace (/(. { 3})/g, "$";
return result;
}
Operation Effect as shown