javascript使用正则表达式格式化货币,金额

来源:互联网 发布:苹果cms模板论坛 编辑:程序博客网 时间:2024/06/07 07:03
var val='212312.235423'
var rex = /\d{1,3}(?=(\d{3})+$)/g;
val.replace(/^(-?)(\d+)((\.\d+)?)$/, function (s, s1, s2, s3) {
          return '$' + s1 + s2.replace(rex, '$&,') + s3;
        })
//"$212,312.235423"


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

str.replace(regexp|substr, newSubStr|function[, flags])
Parameters
--regexp (pattern)
A RegExp object. The match is replaced by the return value of parameter #2.
--substr (pattern)
A String that is to be replaced by newSubStr.
--newSubStr (replacement)
The String that replaces the substring received from parameter #1. A number of special replacement patterns are supported; see the "Specifying a string as a parameter" section below.
--function (replacement)
A function to be invoked to create the new substring (to put in place of the substring received from parameter #1). The arguments supplied to this function are described in the "Specifying a function as a parameter" section below.
--flags  
Note: The flags argument does not work in v8 Core (Chrome and Node.js). A string specifying a combination of regular expression flags. The use of the flags parameter in the String.prototype.replace() method is non-standard and deprecated. Instead of using this parameter, use a RegExp object with the corresponding flags. The value of this parameter if it is used should be a string consisting of one or more of the following characters to affect the operation as described:

g:global match
i:ignore case
m:match over multiple lines
y:sticky


PatternInserts
$$ Inserts a "$".
$& Inserts the matched substring.
$` Inserts the portion of the string that precedes the matched substring.
$' Inserts the portion of the string that follows the matched substring.
$n or $nn Where n or nn are decimal digits, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object.
0 0
原创粉丝点击