This article brings you a detailed explanation of the usage of JavaScript's replace() when passing in the function. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Requirement: Change the number to the left of the floating point point every three digits Add a comma?
var str = '12000000.11'; var res = str.replace(/(\d)(?=(\d{3})+\.)/g, function(s1, s2) { console.log(arguments) // (\d{3})+ 虽然有+但只算一个捕获组 return s2 + ','; // 替换匹配成功的返回值 }); console.log(res) // 12,000,000.11 /* arguments的值为(匹配成功两次): ["2", "2", "000", 1, "12000000.11"] ["0", "0", "000", 4, "12000000.11"] 第一项:匹配成功返回的结果(预测断言匹配成功的值不会出现在匹配结果中) 第二项:第一个捕获组对应的值 第三项:第二个捕获组对应的值 第四项:匹配字符串的索引值 第五项:原始字符串 */
Analysis:
?=exp: Prediction assertion, the position where the assertion appears must match exp, otherwise the match fails, and the length will not be occupied after the match is successful.
/(\d)(?=(\d{3}) .)/g performs global matching. The string that successfully matched for the first time is: "2000000."
The second match The successful string is "0000."
The above is a detailed introduction to the usage of JavaScript's replace() when passing into the function. If you want to know more aboutJavaScript video tutorial, please pay attention to the PHP Chinese website.
The above is the detailed content of Detailed explanation of the usage of JavaScript's replace() when passing in a function. For more information, please follow other related articles on the PHP Chinese website!