JavaScript strings and arrays have many ingenious methods, such as splice, indexOf, and replace, which occasionally produces a pleasing effect in string processing.
For example, the template engine replacement part in underscore, such as the application of credit card segmentation
In short, replace is used to replace some characters in a string with some other characters, the simplest of which is as follows
var num = ' 1234567890123456 '; var numstr = '= num.replace (' 1 ', ' a '); Console.log (NUMSTR);//a234567890123456
This result, in fact, is not ideal, because he only replaced one, the back of the 1 did not talk to me, so this time the regular appeared
var num = ' 1234567890123456 '; var numstr = '= Num.replace (/1/g, ' a '//a234567890a23456
A classic example is the Trim method that JavaScript implements
function () { returnthis. toString (). Replace (/(^\s*) | ( \s*$)/g, ');}; var str = ' Sssssds '; alert (//|sssssds|
There will be some special "$" when the regular appears.
| character |
Replace text |
| $, $ 、...、 |
The text that matches the 1th to 99th sub-expression in RegExp. |
| $& |
A substring that matches the regexp. |
| $` |
The text that is located to the left of the matching substring. |
| $ |
The text on the right side of the matching substring. |
| $$ |
Direct volume symbol. |
var str = ' 123 '; Console.log (str.replace (//- -123----
All is very good time, the unsatisfied situation happened, we feel this result and the expectation does not match, the specific reason we say later, here first look at the function callback condition
var str = ' 123 '; var arr = []; /* Parameter one is matched to the string parameter two is the data corresponding to the subexpression ($i (i:1-99)), such as parentheses will be generated (note that there may be more than one parameter match) parameter three matches the matching string of the last argument to indicate the string itself */ Console.log (str.replace (Match, $, $, offset) { console.log (arguments); Arr.push ('-' + (Match | | ") + '-'); return '-' + (Match | | ") + '-'//- -123----
The above actually want to simply explain the relationship between the function and $, resulting in the output is because the regular is not written to:
var str = ' 123 '; Console.log (Str.replace (
PS: The top of the regular or copy, so later encountered similar problems or have to verify their own.
In addition, I have a credit card account to do format conversion:123456789012 + 1234 5678 9012
This code will not work without a function if it is used with replace.
Once the match succeeds, it is replaced with the return value of the subsequent function, which is called several times, and sometimes we can use it as a loop
var num = ' 123456789012 '; var reg =/\d{4}/g; var index = 0; var arr =function (match, offset) { arr.push (match);}); Console.log (Arr.join (//
Finally, let's take a look at our underscore template engine syntax, now we have a template string, we're going to convert it to a function, so we'll do it.
1 varTemplate = [2' <ul class= ' ul-list "style=" Position:absolute; width:100%; top:0; left:0; " > ',3' <%for (var i = 0, len = data.length; i < Len; i++) {%> ',4' <li data-key= ' <%=data[i].id%> "data-index=" <%=i%> "<%if (data[i].disabled) {%> class=" disabled "‘,5' <%}%>> ',6' <%=data[i].name%></li> ',7' <%}%> ',8' </ul> ',9' <div class= ' cui-mask-gray ' > ',Ten' </div> ', One' <div class= ' cui-lines ' > ', A' </div> ' -].join (' '); - the varEscapes = { -"‘": "‘", -‘\\‘: ‘\\‘, -\ R ': ' R ', +' \ nthe ': ' N ', -' t ': ', +' \u2028 ': ' u2028 ', A' \u2029 ': ' u2029 ' at }; - varEscaper =/\\| ' | \r|\n|\t|\u2028|\u2029/G; - - varindex = 0; - varSource = "__p+="; - varMatcher =/(<%-[\s\s]+?) %>|<%= ([\s\s]+?) %>|<% ([\s\s]+?) %>|$/G; in -Template.replace (Matcher,function(match, Escape, interpolate, evaluate, offset) { toSOURCE + =template.slice (index, offset) +. replace (Escaper,function(match) {return' \ \ ' +Escapes[match];}); - the if(Escape) { *SOURCE + = "' +\n ((__t= (" + Escape + ")) ==null? ': _.escape (__t)) +\n '"; $ }Panax Notoginseng if(interpolate) { -SOURCE + = "' +\n ((__t= (" + interpolate + ") ==null? ': __t) +\n '"; the } + if(evaluate) { ASOURCE + = "'; \ n" + Evaluate + "\n__p+="; the } +Index = offset +match.length; - returnmatch; $ }); $SOURCE + = "'; \ n"; - -Source = ' With (obj| | {}) {\ n ' + source + '}\n '; the -Source = "Var __t,__p=", __j=array.prototype.join, "+Wuyi"Print=function () {__p+=__j.call (arguments,");};\ N "+ theSOURCE + "Return __p;\n"; - WuConsole.log (source);
The above code prints out something:
var__t,__p= ', __j=array.prototype.join,print=function() {__p+=__j.call (arguments, ");}; with(obj| |{}) {__p+ = ' <ul class= "ul-list" style= "Position:absolute; width:100%; top:0; left:0; " > '; for(vari = 0, len = data.length; i < Len; i++) {__p+ = ' <li data-key= ' +((__t= (data[i].id)) = =NULL? ': __t) + ' "data-index=" ' +((__t= (i)) = =NULL? ": __t) + '" ';if(data[i].disabled) {__p+ = ' class= ' disabled "';} __p+ = ' > ' +((__t= (data[i].name)) = =NULL? ": __t) + ' </li> ';} __p+ = ' </ul><div class= "Cui-mask-gray" ></div><div class= "Cui-lines" > </div> ';}return__p;
Code complexity slightly increased, but the principle of the same as above, you read it yourselves, today's study to this
"Tips" Explore Replace in JavaScript