How to Implement replaceall in javascript

Source: Internet
Author: User

The replace function is used to replace strings in javascript, but in actual use, it is found that this function only replaces the first character to be matched, which makes people very uncomfortable, in php, replace implements global matching and replacement. No way. After careful research, we found that there are other ways to achieve global matching and replace it.

(1) In fact, replace itself can also implement this function, but you need to add a parameter g in the form of a regular expression, for example:

str.replace(/www.baidu.com/g,'www.phpernote.com');

Or:

str.replace(new RegExp('www.baidu.com','gm'),'www.phpernote.com');

Replace www.baidu.com with www.phpernote.com.

(2) Expand the js function library and use the replaceall method to implement global matching and replacement. As follows:

String.prototype.replaceall=function(s1,s2){return this.replace(new RegExp(s1,"gm"),s2); }

This is actually using method 1. For example ):

str.replace('www.baidu.com','www.phpernote.com');
Articles you may be interested in
  • MySQL replace function replacement string statement usage
  • Vcastr 3.0-detailed instructions on downloading and configuration of flash video (flvplayer)
  • Php string replacement function str_replace is faster than preg_replace
  • Summary of the string truncation function implemented by javascript (including introduction to the use of Js to intercept Chinese characters)
  • JQuery adds Event Response to dynamically generated content (jquery live Method Introduction)
  • Php $ GLOBALS super global variable analysis
  • Note the following when querying strings with single quotes and inserting strings with single quotes in Mysql:
  • Js reports TypeError $ (...) is null error, causes of jquery failure and Solutions

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.