您的位置:首页 > Web前端 > JavaScript

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

2015-08-19 14:42 681 查看
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

Pattern
Inserts

$$ 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.
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息