Use of the replace () method in javascript _ javascript skills

Source: Internet
Author: User
In JavaScript, the replace function returns a copy of the string after text replacement based on the regular expression. Usage: stringObj is required. String object or String text to be replaced. Recently, I was browsing some of Alibaba's front-end questions. one of these questions relates to the use of the replace () method in javascript. The following is the original question:

"What is the role of the following functions? What should I enter in the blank area ?"

 // define  (function (window) {    function fn(str) {      this.str = str;    }    fn.prototype.format = function () {      var arg = ______;      return this.str.replace(_______, function (a, b) {        return arg[b] || '';      });    }    window.fn = fn;  })(window);  // use  (function(){    var t = new fn('

{1}{2}

'); console.log( t.format('http://www.alibaba.com', 'Alibaba', 'Welcome') ); })();

The following is the analysis process (I think it is more organized to get a number)

1. this question also involves other knowledge points, such as anonymous functions and prototypes, but it is not the focus of this discussion.

2. based on the question surface, we know that the source code of this question is similar to writing a template engine. Replace the placeholder '{1}' in the template with the parameter passed to it. So arg should be arguments. But !!! Because arg is not an array, but an array object of the class (Baidu (u_u), we need to perform some conversions,

The code is as follows:

Var arg = Array. prototype. slice. call (arguments, 0 );

3. the answer to the right of the equal sign is the empty answer. After talking about this, the second question is the focus of our discussion ~~~~~~ We all know that the second null is to use regular expressions to find placeholders and replace them with strings in the arg array based on the numbers in the placeholders, to be honest, the second parameter of the replace method is rarely used when it is a function. Generally, this is the case. let's look at the following code:

The code is as follows:


Var pattern =/8 (. *) 8 /;
Var str = 'This is a 8baidu8 ';
Document. write (str. replace (pattern ,'$1'));

4. since the second replace parameter is a function, we will focus on the situation where the second parameter is a function.

First, this is the syntax of the replace function: stringobject. replace (regexp/substr, replacement)

Regexp/substr is required. Specifies the regexp object of the string or pattern to be replaced. (Note that if the value is a string, it is used as the direct text mode to be retrieved, rather than being converted to a regexp object first .) Replacement is required. A string value. Specifies the function for replacing text or generating replacement text. Finally, a new string is returned, which is obtained after the first match or all matches of regexp are replaced by replacement.

5. ECMAScript stipulates that the replacement parameter of the replace () method can be a function rather than a string. In this case, each match calls this function, and the string it returns will replace the text. The first parameter indicates the matched characters, the second parameter indicates the minimum index position (RegExp. index) of the matched characters, and the third parameter indicates the matched string (RegExp. input ).

6. Therefore, the second null value can be written as follows: // \ {(\ d +) \}/g. The complete statement is:

The code is as follows:


Return this. str. replace (/\ {(\ d +) \}/g, function (a, B ){
Return arg [B] | '';
});

When the first match is executed, {0} is replaced with arg [0]
When the first match is executed, {1} is replaced by arg [1]
When the first match is executed, {2} is replaced with arg [2]

7. the above is the second parameter of the js string method replace () to explain the function (if there are any imperfections, add them on your own). of course, this question has solved ~~~~~

The above is all the content of this article. I hope you will like it.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.