Home  >  Article  >  Web Front-end  >  Detailed explanation of the usage of JavaScript's replace() when passing in a function

Detailed explanation of the usage of JavaScript's replace() when passing in a function

云罗郡主
云罗郡主forward
2018-10-19 14:11:192105browse

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.

Detailed explanation of the usage of JavaScripts replace() when passing in a function

Basic usage:

<script>
var str = "a1ba2b";
var reg = /a.b/g;
str = str.replace(reg,function(a,b){
	console.log(a);
	console.log(b);
	return b == 0 ? a.replace("a","0") : a.replace("b","3");
});
console.log(str);

/*
  输出结果为:
  a1b
  0//第一次匹配到a1b,将a置为0.
  a2b
  3//第二次匹配到a2b,将b置为3.
  01ba23//返回经过修改后的字符串
*/
/*
  function(a,b,c)一共可以传入3个参数,第一个为匹配的字符串,第二个为匹配字符串的起始位置,
  第三个为调用replace方法的字符串本身。可以缺省c或b、c。
*/
</script>

Usage when using capturing group:

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!

Statement:
This article is reproduced at:csdn.net. If there is any infringement, please contact admin@php.cn delete