A string that is known to be #####, now needs to replace the # of the even position with &.
function Replacedemo () { var s = "1#2#3#4#5#"; var regex =/#/g; var index = 1; S=s.replace (regex,function() {index++; Return index%2? ' & ': Arguments[0]}); return s; }
Comments:
1. Because the entire string needs to be matched, the policy expression needs to add the G parameter.
2.index is used to record the position of a character matched to a regular expression to find the character of an even position.
3.arguments is an internal object? Arguments[0] is the match to the character value, where #;arguments[1] is the match to the character value at the position of the original string.
A string of $$$$$ is known, and it is now necessary to replace the $ & for even position.
function Replacedemo () { var s = "$$$$$"; var // /$/g; var index = 1; S=s.replace (regex,function() {index++; Return index%2? ' & ': Arguments[0]}); return s; }
Comments:
1. Special symbol $ in regular expressions The meaning of the match string end position. Need to escape by//symbol when matching
JavaScript matches the character of the even position of the string and matches the $ symbol