Use the replaceAll () function in javascript to replace characters

Source: Internet
Author: User

Str. replace (/\-/g ,"! "), You can replace all matched characters (g is the global flag ).
Replace ()
The replace () method returns the string that results when you replace text matching its first argument
(A regular expression) with the text of the second argument (a string ).
If the g (global) flag is not set in the regular expression declaration, this method replaces only the first
Occurrence of the pattern. For example,
Var s = "Hello. Regexps are fun."; s = s. replace (/\./,"! "); // Replace first period with an exclamation pointalert (s );
Produces the string "Hello! Regexps are fun. "Including the g flag will cause the interpreter
Perform a global replace, finding and replacing every matching substring. For example,
Var s = "Hello. Regexps are fun."; s = s. replace (/\./g ,"! "); // Replace all periods with exclamation pointsalert (s );
Yields this result: "Hello! Regexps are fun !"
You can use the following methods .:
String. replace (/reallyDo/g, replaceWith );
String. replace (new RegExp (reallyDo, 'G'), replaceWith );
String: the string expression contains the substring to be replaced.
ReallyDo: The substring to be searched.
ReplaceWith: The substring to replace. Copy codeThe Code is as follows: <script type = "text/javascript">
String. prototype. replaceAll = function (reallyDo, replaceWith, ignoreCase ){
If (! RegExp. prototype. isPrototypeOf (reallyDo )){
Return this. replace (new RegExp (reallyDo, (ignoreCase? "Gi": "g"), replaceWith );
} Else {
Return this. replace (reallyDo, replaceWith );
}
}
</Script>
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.