JS string Replacement-no replaceall replace all strings solution __js

Source: Internet
Author: User
JS replaces all strings-no replaceall solution

Native JS does not have the ReplaceAll method, only replace, if you want to replace the string, general use replace

var str = ' 2016-09-19 ';
var result = str.replace ('-', ', ');
Console.log (result);
...
201609-19

Replace replaces only the first original character found, and if you want to replace all strings, there are two scenarios: (1) The regular expression replaces all characters

You need to use regular expressions:

var str = ' 2016-09-19 ';
var result = Str.replace (/-/g, "");
Console.log (result);
...
20160919

/-/g/-is to be-escaped,/g represents the replacement of all strings. (2) string decomposition join substitution method

var str = ' 2016-09-19 ';
var result = Str.split ('-'). Join (');
Console.log (result);
...
20160919
(3)? Custom Function

The above two ways are more flexible, but if you want to write once, the other place directly call, it is necessary to customize the extension JS function library
Add script code to HTML

 

Of course, you can also create a separate utils js file, and then write the code into this file, and then refer to:

<script language= "javascript" type= "Text/javascript" src= "Js/utils.js" ></script>

Note: There are no <script> tags in the utils.js file

String.prototype.replaceAll = function (FindText, reptext) {
REGEXP = new RegExp (FindText, "G");
Return This.replace (REGEXP, Reptext);
}

Then you can use the JS code directly

var str = ' 2016-09-19 ';
var result = Str.replaceall ('-', ', ');
Console.log (result);
...
20160919

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.