JavaScript positive expression Reverse Reference example Introduction _ Regular Expression

Source: Internet
Author: User
Recently encountered a requirement to pass in a string, insert a space every three characters

Cases:

Incoming abcd1234

Output ABC D12 34

Think for a moment, ready to write a function as follows
Copy Code code as follows:

function Appendspace (s)
{
var length = s.length;
var result = "";
var last = 0;
for (var i = 3;i<=length;i=i+3,last = last+3)
{
result = Result+s.substring (i-3,i) + "";
}
result = Result+s.substring (last,length);
return result;
}

Feel this function is a bit of a dick silk ...

and replaced the Replace () regular expression substitution method
Copy Code code as follows:

/*
*$1 represents the first pair of parentheses in a reference matching rule (here is "(. { 3}) "") Hits the text
* Direct output when no parenthesis is added
*/
function Insertspace (s)
{
var result =s.replace (/(. { 3})/g, "$";
return result;
}

Operation Effect as shown

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.