JavaScript matches the character of the even position of the string and matches the $ symbol

Source: Internet
Author: User

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

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.