Defined
The replace () function is used for replacing strings.
Grammar
Stringobject.replace (Regexp/substr, newsubstr/function)
Parameters
REGEXP/SUBSTR Regular Expression/string
Newsubstr/function Replace text/Generate alternate text function
Example
var str = "Visit microsoft!"; var res = str.replace ("Microsoft", "W3Schools");
Replace character
What does it mean if the replacement string Newsubstr contains the $ character?
A text that matches the 1th to 99th sub-expression in the $, $, ..., $ $ and regexp
$& and regexp matching substring
$ ' text on the left side of the matching substring
$ ' text on the right side of the matching substring
$$ Direct volume symbol.
What is the meaning of the sub-expression mentioned in the above $, $ ... An expression enclosed in parentheses in a regular expression.
/a/No sub-expression
/[a]/No sub-expression
/(a)/have sub-expression (a)
/(a), (b)/have sub-expressions (a), (b)
Example
Name = "Doe, John"; Name.replace (/(\w+) \s*, \s* (\w+)/, "$ $");//output "John Doe"
Replace function
Replace function description
function (Match, p1, P2,..., offset, string)
Match matches to the string
P1, p2 ... Sub-expression to match
Offset matches the position of the string
String Entire string
Example
var name = "Ace:mm-abc". Replace (/([\:\-\_]+ (.)) /, function (Match, p1, P2, offset, total) {Console.log ("match:" + _); Console.log ("P1:" + separator); Console.log ("P2:" + letter); Console.log ("offset:" + offset); Console.log ("total:" + All) return offset? P2.touppercase (): p2;}) Console.log (name)/* Output substr::m TEST.HTML:43P1::MP2:MOFFSET:3TOTAL:ACE:MM-ABCACEMM-ABC */
There are two sub-expressions in the above regular expression
P1 is a sub-expression ([\:\-\_]+ (.)) Match to the content ": M"
P2 is a child form (.) Match to the content "M"