JS string replacement (using replace() method)

The second parameter of the replace() method can use a function. This function will be called when matching. The return value of the function will be used as the replacement text. At the same time, the function can receive special characters $as .

Agreed string illustrate
$1、$2、…、$99 Text matching the 1st to 99th subexpression in the regular expression
$& (dollar sign + hyphen) Substring matching regular expression
$' (dollar sign + switch skill key) text to the left of the matched substring
$' (dollar sign + single quote) Text to the right of the matched string
$$ Represents $ string

Example 1

The following code converts the first letter of each word in the string to uppercase and displays it.

  1. var s = 'javascript is script , is not java.'; //定义字符串
  2. //定义替换文本函数,参数为第一个子表达式匹配文本
  3. var f = function ($1) {
  4. //把匹配文本的首字母转换为大写
  5. return $1.substring(0,1).toUpperCase() + $1.substring(1).toLowerCase();}
  6. var a = s.replace(/(\b\w+\b)/g, f); //匹配文本并进行替换
  7. console.log(a); //返回字符串“JavaScript Is Script , Is Not Java.”

In the above example, replace the parameter of the function with the special character "$1", which represents the text matched by the parentheses in the regular expression /(\b\w+\b)/, and then process the matching text within the function structure and intercept it. The first letter is converted to uppercase, the remaining characters are all lowercase, and the newly processed string is returned. The replace() method uses the returned new string to replace each matching substring in the original text.

Example 2

The above example can be extended further and use parentheses to obtain more matching information. For example, if you directly use parentheses to pass the first letter of a word, and then perform case conversion processing, the processing result will be the same.

  1. var s = 'javascript is script , is not java.'; //定义字符串
  2. var f = function ($1,$2,$3) { //定义替换文本函数,请注意参数的变化
  3. return $2.toUpperCase() + $3;
  4. }
  5. var a = s.replace(/(\b\w+\b)/g, f);
  6. console.log(a);

In the function f(), the first parameter represents the text matched each time, the second parameter represents the text matched by the subexpression of the first parenthesis, that is, the first letter of the word, and the second parameter represents the second The text matched by the subexpression in parentheses.

The second parameter of the replace() method is a function, and the replace() method will pass it multiple actual parameters. These actual parameters have certain meanings, as detailed below.

  • The first parameter represents the text that matches the match pattern, such as the word string matched each time in the example above.
  • The subsequent parameters are strings that match the subexpressions in the matching pattern. The number of parameters is not limited and depends on the number of subexpressions.
  • The following parameter is an integer, indicating the subscript position of the matching text in the string.
  • The last parameter represents the string itself.

Example 3

Change the text replacement function in the above example to the following form.

  1. var f = function() {
  2. return arguments[1].toUpperCase() + arguments[2];
  3. }

That is to say, if you do not pass formal parameters to the function, you can also read the relevant matching text information in the regular expression by directly calling the arguments attribute of the function. in:

  • arguments[0]: Indicates the text matched each time, that is, the word.
  • arguments[1]: Indicates the text matched by the first subexpression, that is, the first letter of the word.
  • arguments[2]: Indicates the text matched by the second subexpression, that is, the remaining letters of the word.
  • arguments[3]: Indicates the subscript position of the matching text. For example, the subscript position of the first matching word "javascript" is 0, and so on.
  • arguments[4]: Indicates the string to be matched, here it means "javascript is script, is not java.".

Example 4

The following code uses the arguments object of the function to actively obtain the detailed information matched by the regular expression in the first parameter of the replace() method.

  1. var s = 'javascript is script , is not java.'; //定义字符串
  2. var f = function () {
  3. for (var i = 0; i < arguments.length; i++) {
  4. console.log("第" + (i + 1) + "个参数的值:"+ arguments[i]);
  5. }
  6. console.log("-----------------------------");
  7. }
  8. var a = s.replace(/(\b\w+\b)/g, f);

In the function structure, when using the for loop structure to traverse the arguments attribute, it is found that each time a word is matched, a prompt message will pop up 5 times, respectively displaying the matching text information listed above. Among them, arguments[1] and arguments[2] will respectively display the matching information of the subexpression in the current matching text according to the difference of each matching text, and arguments[3] will display the subscript position of the current matching word. Arguments[0] always displays the word matched each time, and arguments[4] always displays the string being operated on.

Example 5

The following code design reads student scores (JSON format) from the server side, and then uses the for statement to convert all data into strings. Let's practice automatically extracting the scores in the string, summarizing and calculating the average score. Finally, use the replace() method to extract each score and compare it with the average score to determine the specific information of the replacement text.

  1. var scope = {
  2. "张三" : 56,
  3. "李四" : 76,
  4. "王五" : 87,
  5. "赵六" : 98
  6. }, _scope = "";
  7. for (var id in scope) { //把JSON数据转换为字符串
  8. _scope += id + scope[id];
  9. }
  10. var a = _scope.match(/\d+/g), sum = 0; //匹配出所有分值,输出位数组
  11. for (var i = 0; i <a.length; i++) { //遍历数组,求总分
  12. sum += parseFloat(a[i]); //把元素值转换为数值后递加
  13. };
  14. var avg = sum / a.length; //求平均分
  15. function f() {
  16. var n = parseFloat(arguments[1]); //把匹配的分数转换为数值,第一个子表达式
  17. return ":" + n + "分" + "(" + ((n > avg) ? ("超出平均分" + (n - avg)) :
  18. ("低于平均分" + (avg - n))) + "分)<br>"; //设计替换文本的内容
  19. }
  20. var s1 = _scope.replace(/(\b\w+\b)/g, f); //执行匹配、替换操作
  21. document.write(s1);

The running results are as follows:

The for/in statement cannot be used when traversing the array because other related matching text information is also stored in the array. It should be implemented using the for structure. Since the intercepted numbers are all string types, they should be converted to numerical types, and then the numbers should be concatenated together, or compared in alphabetical order, etc.

Guess you like

Origin blog.csdn.net/unbelievevc/article/details/128076920