Last active
July 3, 2018 09:55
-
-
Save langjt/99bb8927e002558825c1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 方法一:string | |
function thousandSymbol(str) { | |
if (typeof str !== 'string') { | |
return str; | |
} | |
var iNum = str.length % 3, | |
prev = '', | |
arr = []; | |
if (iNum != 0) { | |
prev = str.substring(0, iNum); | |
arr.push(prev); | |
} | |
str = str.substring(iNum); | |
for (var i= 0,len=(str.length/3); i<len; i++) { | |
arr.push(str.substr(i, 3)); | |
} | |
return arr.join(','); | |
} | |
// 方法二:正则(前向声明/反前向声明) | |
function thousandSymbolReg(str) { | |
if (typeof str !== 'string') { | |
return str; | |
} | |
return str.replace(/(?=(?!\b)(\d{3})+$)/g, ','); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment