Substring and splice for common JavaScript function exercises

Source: Internet
Author: User

Question: Add a separator for each n characters of a given string, which is implemented by substring or splice.

Syntax

1) substring() Method is used to extract characters that are intermediary between two specified subscripts of a string.
Syntax
StringObject. substring (start, stop)
Start is required. A non-negative integer that specifies the position of the first character of the substring to be extracted in the stringObject.
Optional. A non-negative integer is 1 more than the position of the last character of the substring to be extracted in the stringObject. If this parameter is omitted, the returned substring ends at the end of the string.


2) splice() Method to add/delete a project to/from the array, and then return the deleted project.

Note: This method will change the original array.
Syntax
ArrayObject. splice (index, howmany, item1,..., itemX)
Index is required. Integer that specifies the position of the added/deleted project. A negative number can be specified from the end of the array.
Howmany is required. The number of projects to delete. If it is set to 0, the project will not be deleted.
Item1,..., itemX (optional. Add a new project to the array.

Implementation

// Function addComma (str, n, separator) {var tempArr = []; for (var I = str. length; I> = n; I = I-n) {tempArr. push (str. substring (I-n, I) ;}; if (I> 0) {tempArr. push (str. substring (0, I);} str = tempArr. reverse (). join (separator); return str ;}
// Method 2: function addComma1 (str, n, separator) {var tempArr = []; var strArr = str. split (""); for (var I = strArr. length; I> = n; I = I-n) {strArr. splice (I-n, 0, separator) ;}; str = strArr. join (""); return str ;}
// Test alert (addComma ("fasdfas dafsdfsdf fadsfasdfa", 6, "| "));


Related Article

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.