JS replaces all specified characters in the string

Source: Internet
Author: User

The first time you find the Replace () method in JavaScript If you use Str.replace directly ("-", "!") Only the first matching character is replaced.
and Str.replace (/\-/g, "!") You can replace all matching characters (G is the global flag).

Replace ()
The Replace () method returns the string that results if 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 is fun. " ; s = s.replace (/\./, "!"  ); Replace first period with an exclamation pointalert (s);

Produces the string "hello! Regexps is fun. " Including the G flag would cause the interpreter to
Perform a global replace, finding and replacing every matching substring. For example,

var s = "Hello." Regexps is fun. " ; s = s.replace (/\./g, "!"  ); Replace all periods with exclamation pointsalert (s);

Yields this result: "hello! Regexps is fun! "

So there are several ways to do this:
String.Replace (/reallydo/g, replacewith);
String.Replace (New RegExp (Reallydo, ' G '), replacewith);

string expression containing the substring to be substituted.
Reallydo: the substring being searched.
ReplaceWith: Substring used for substitution.

JS Code 
  1. <script type="Text/javascript" >
  2. String.prototype.replaceAll = function (Reallydo, replacewith, ignoreCase) {
  3. if (! RegExp.prototype.isPrototypeOf (Reallydo)) {
  4. return this.replace (new RegExp (Reallydo, ignoreCase?  " gi": "G")), replacewith);
  5. } Else {
  6. return this.replace (Reallydo, replacewith);
  7. }
  8. }
  9. </script>

Source: http://fuleonardo.iteye.com/blog/339749

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.