In-depth analysis of Javascript replace function usage

Source: Internet
Author: User

This article briefly introduces the usage of the Javascript replace function. To facilitate your understanding, I believe this article will surely help you gain some benefits.

Javascript replace Function

If you use str. replace ("-","! ") Will only replace the first matched character. str. replace (/-/g ,"! ).

Replace Method

Syntax

StringObj. replace (rgExp, replaceText)

The syntax of the replace method includes the following parts:

Partial description

StringObj is required. String object or text to be replaced. This object will not be modified by the replace method.

RgExp is required. A regular expression object that describes the content to be searched.

ReplaceText is required. Is a String object or text. For each position in stringObj that matches rgExp, it is replaced by the text contained in this object.

The following example demonstrates how to use the replace method in Javascript:

 
 
  1. functionReplaceDemo()  
  2. {  
  3. varr,re;  
  4. vars="Thequickbrownfoxjumpedoverthelazyyellowdog.";  
  5. re=/fox/i;  
  6. r=s.replace(re,"pig");  
  7. return(r);  
  8. }  

In addition, the replace method can replace the subexpression in the mode. The following example demonstrates each pair of words in the exchange string:

 
 
  1. FunctionReplaceDemo ()
  2. {
  3. Varr, re;
  4. Vars = "Thequickbrownfoxjumpedoverthelazyyellowdog .";
  5. Re =/(S +) (s +) (S +)/g;
  6. R = s. replace (re, "$3 $2 $1"); // exchange each pair of words.
  7. Return (r );
  8. }

If the replace () method in JavaScript uses str. replace ("-","! ") Only the first matched character. str. replace (/-/g ,"! ).

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.