


Parameter usage when the second parameter of javascript replace() is a function (detailed explanation for everyone)
The replace() function has a replacement function. It can have two parameters. The first parameter can be the string to be replaced or a regular expression matching the string to be replaced. The second parameter can be the replacement text. Or a function, let’s take a look at a few code examples about the replace() function
The second parameter of JavaScript’s replace() is the parameter of the function:
Thereplace() function has replacement Function, it can have two parameters. The first parameter can be the string to be replaced or a regular expression matching the string to be replaced. The second parameter can be the replacement text or a function. Let’s take a look at replace Several code examples of the () function.
Code example:
Example 1:
<script> var str="I love jb51 and you?"; console.log(str.replace("jb","java")); </script>
The above code can only replace the first specified substring in the string.
Example 2:
<script> var str="I love jb51 and you?"; var reg=/jb/g; console.log(str.replace(reg,"java")); </script>
The above code can replace all specified substrings in the string.
Example 3:
<script> var str="I love jb51 and you?"; console.log(str.replace("jb",function(){ return "java"} )); </script>
In the above code, the second parameter is a function, and the return value of this function can be used to replace the specified string substring. When the second parameter is a function, the function can actually pass parameters. Let's introduce the parameter issues of the function through code examples.
The code is as follows:
<!DOCTYPE html> <html> <head> <meta charset=" utf-8"> <title>脚本之家</title> <script type="text/javascript"> var url = "http://www.jb51.net/o.php?mod=viewthread&tid=14743&extra=page%3D1"; //第一参数为字符串 console.group("字符串"); var oneResult = url.replace("www.jb51.net",function(){ console.log("replace输入参数:%o",arguments); var val = /www.jb51.net/.exec(url); console.log("exec输出参数:%o",val); console.assert(arguments[0] === val[0]); console.assert(arguments[1] === val["index"]); console.assert(arguments[2] === val["input"]); return "jb51"; }); console.log("replace返回字符串:"+oneResult); console.groupEnd("字符串"); //第一参数为正则表达式 console.group("正则表达式"); var regexp_global = /[?&](\w+)=([^&]*)/g; var count = 0; var twoResult = url.replace(regexp_global,function(){ console.log("第"+(count++)+"次运行"); console.log("replace输入参数:%o",arguments); var val = regexp_global.exec(url); console.log("exec输出参数:%o",val); console.assert(arguments[0] === val[0]); console.assert(arguments[1] === val[1]); console.assert(arguments[2] === val[2]); console.assert(arguments[3] === val["index"]); console.assert(arguments[4] === val["input"]); return count; }); console.log("replace返回字符串:"+twoResult); console.groupEnd("正则表达式"); </script> </head> <body> </body> </html>
In the above code, it is demonstrated that the first parameter of the replace() function is an ordinary string and a regular expression. When the second function parameter passes parameters, a brief explanation will be given below:
The first parameter is an ordinary string:
When the first parameter is an ordinary string, Then only the first substring in the original string will be replaced, that is to say, only one replacement operation will be performed, for the parameters passed to the function and the array returned by the exec() function using ordinary string parameters as regular expressions. The elements are the same.
The first parameter is a regular expression:
Due to space reasons, only part of the running results are intercepted here. The first parameter of the replace() function is a regular expression, and the execution is global. match, then the second function parameter will be called multiple times, and the parameters passed each time are the same as the element contents of the array returned by regexp_global.exec(url).
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
Use js to get the week of the year today is (small example, with source code)
Talk about HTML CSS JS (detailed explanation)
About how to optimize your JS code (graphic tutorial)
The above is the detailed content of Parameter usage when the second parameter of javascript replace() is a function (detailed explanation for everyone). For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Atom editor mac version download
The most popular open source editor

SublimeText3 Linux new version
SublimeText3 Linux latest version

SublimeText3 Mac version
God-level code editing software (SublimeText3)

SublimeText3 English version
Recommended: Win version, supports code prompts!

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.