The use of Replace in JS

Source: Internet
Author: User

The syntax for the Replace method is: Stringobj.replace (rgexp, ReplaceText) where Stringobj is a string (string), Reexp can be a regular expression object (REGEXP) or it can be a string ( String), ReplaceText is the alternative to finding the string: To help you understand better, here's a simple example to illustrate

JS Code
    1. <script language="JavaScript" >
    2. var stringobj="The end of the ancient People's Republic, the end of the ancient people";
    3. Replace the typo "the end ancient" for "China"
    4. and returns the new character after the replacement
    5. The value of the original string stringobj has not changed
    6. var newstr=stringobj.replace ("End Ancient","China");
    7. alert (NEWSTR);
    8. </script>



You are smarter than me, after reading the above example, you will find that the second typo "end ancient" has not been replaced with "China", we can execute two times replace method to replace the second typo "End Ancient", the program has been improved as follows:

JS Code
    1. <script language= "JavaScript" >   
    2. var  stringobj= "The end of the ancient People's Republic, the end of the ancient people";   
    3.   
    4. //replace typos "the end ancient" for "China" &NBSP;&NBSP;&NBSP;
    5. span class= "comment" >//and returns the replacement of the new character    
    6. //the value of the original string stringobj has not changed    
    7. var  newstr=stringobj.replace ( Span class= "string" > "End Ancient", "China");   
    8.   
    9. newstr=newstr.replace ( "End Ancient" , "China");   
    10. alert (NEWSTR);   
    11. </script>  


We can carefully think about, if there is N of the N-square typos, is not also to execute n the N-square replace method to replace the typos?? Oh, don't be afraid, with a regular expression after the use of a typo to perform a replace method. The code after the program has been improved is as follows

JS Code
    1. <script language="JavaScript" >
    2. var reg=new RegExp ("End Ancient","G"); //Create regular RegExp object
    3. var stringobj="The end of the ancient People's Republic, the end of the ancient people";
    4. var newstr=stringobj.replace (Reg,"China");
    5. alert (NEWSTR);
    6. </script>


Above is the Replace method of the simplest application, do not know if you understand?? Let's start with a slightly more complex application.


When you search for articles on some websites, you will find this phenomenon, that is, the search keywords will be highlighted to change the color display?? How is this achieved?? In fact, we can use regular expressions to achieve, specifically how to achieve it? See the following code for a simple principle

JS Code
    1. <script language="JavaScript" >
    2. var str="People's Republic of China";
    3. var newstr=str.replace (/(person)/g,"<font color=red>$1</font>");
    4. document.write (NEWSTR);
    5. </script>


The above program is lack of interactivity, we can improve the program, to achieve the self-input to find the character

JS Code
    1. <script language= "JavaScript" >   
    2. var  s=prompt ( "Please enter the characters in Search",
    3. var  reg= new  regexp ( "G");   
    4. var  str=< Span class= "string" > "People's Republic of China, PRC";   
    5. var  newstr=str.replace (reg,< Span class= "string" > "<font color=red>$1</font>");   
    6. document.write (NEWSTR);   
    7. </script>  


It may be that everyone will be able to express what the meaning of the special character is not very understanding, in fact, is the expression in the left side of the parentheses in the character, that is, the first sub-match, the same can be a second sub-match: What is a sub-match?? Popular point, is the left each parenthesis is the first word match, the second parenthesis is the second sub-match:


How do we do this when we are going to do the arithmetic of the found character?? Before we do that, let's talk about how to get the arguments for a function: Within function functions, there is a arguments collection, which stores all the parameters of the current function, and through arguments can get all the parameters of the function, for your understanding, see the following code

JS Code
    1. <script language="JavaScript" >
    2. function Test () {
    3. Alert ("Number of parameters:" +arguments.length);
    4. Alert ("value of each parameter:" +arguments[0]);
    5. Alert ("The value of the second parameter" +arguments[1]);
    6. //can read all parameters with a for loop
    7. }
    8. Test ("AA","BB","CC");
    9. </script>



After reading the above procedure, let's take a look at the following interesting program

JS Code
    1. <script language="JavaScript" >
    2. var reg=new RegExp ("\\d","G");
    3. var str="ABD1AFA4SDF";
    4. Str.replace (Reg,function() {alert (arguments.length);});
    5. </script>


We were surprised to find that the anonymous function has been executed two times, and in the function also has three parameters, why the execution two times?? This is easy to think, because the regular expression we write is matched to a single number, and the string being detected has exactly two digits, so the anonymous function was executed two times. What exactly is the three parameters inside the anonymous function?? To understand the problem, let's look at the following code.

JS Code
    1. <script language= "JavaScript" >   
    2. function  test () {  
    3. for ( var  i=0;i<arguments.length;i++) {  
    4.     alert ( "+" + (i+1) +
    5. }   
    6. }   
    7. var  reg= new  regexp ( "\\d", "G");   
    8. var  str= "ABD1AFA4SDF";   
    9. str.replace (reg,test);   
    10. </script>  


After observation we found that the first parameter represents the matched character, the second parameter represents the minimum index position (regexp.index) of the character at the time of the match, and the third parameter represents the matched string (regexp.input). In fact, the number of these parameters, but also with the sub-matching more and more changes. After figuring out these questions, we can use a different kind of notation

JS Code
  1. <script language="JavaScript" >
  2. function Test ($) {
  3. return "<font color= ' Red ' >" +$1+"</font>"
  4. }
  5. var s=prompt ("Please enter the character in the lookup","person");
  6. var reg=new RegExp ("(" +s+")","G");
  7. var str="People's Republic of China";
  8. var newstr=str.replace (reg,test);
  9. document.write (NEWSTR);
  10. </script>


Look at the above program, the original can be matched to the character as you pleases. Here's a quick example of an application

JS Code
  1. <script language="JavaScript" >
  2. var str="He is 22 years old, she is 20 years old, his father is 45 years old, her father this year 44 years old, a total of 4 people"
  3. function Test ($) {
  4. var gyear= (new Date ()). GetYear ()-parseint ($ +1);
  5. return $1+"(" +gyear+"year of birth)";
  6. }
  7. var reg=new RegExp ("(\\d+) years old","G");
  8. var newstr=str.replace (reg,test);
  9. alert (str);
  10. alert (NEWSTR);
  11. </script>

Use of Replace in JS

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.