Using split(), slice(), splice(), join() respectively, methods of manipulating arrays

Directory

Foreword:

What is split()? What does it do? How to use it?

What is join()? What does it do? How to use it?

What is slice()? What does it do? How to use it?

What is splice()? What does it do? How to use it?


Foreword:

We need to know split(), join(), slice(), splice(), what do these methods do, what are their uses, and how to use them:

Here is a brief description of these methods:

  1. split(): The split() JavaScript method is used to split a string into substrings and store the result in an array. It takes a delimiter as an argument, splits the string according to the delimiter, and returns an array containing the split substrings.

    Usage example:

    const str = "Hello, World!";
    const arr = str.split(","); // Split the string into an array by commas
    console.log(arr); // output: ["Hello", "World!"]
    
  2. join(): The join() method is used to join all the elements in the array into a string. It takes an optional delimiter as a parameter, concatenates the elements in the array with this delimiter, and returns the concatenated string.

    Usage example:

    const arr = ["Hello", "World!"];
    const str = arr.join(","); // Join the elements in the array into a string with commas
    console.log(str); // Output: "Hello, World!"
    
  3. slice(): The slice() method is used to extract the specified range of elements from a string or array and return a new string or array. It takes a start index and an optional end index as arguments, and returns the elements from the start index to the end index (excluding the end index).

    Usage example:

    const str = "Hello, World!";
    const slicedStr = str.slice(7, 12); // extract substring from index 7 to index 11
    console.log(slicedStr); // output: "World"
    
    const arr = [1, 2, 3, 4, 5];
    const slicedArr = arr.slice(2, 4); // extract subarray from index 2 to index 3
    console.log(slicedArr); // output: [3, 4]
    
    1. splice(): The splice() method is used to add, delete or replace elements from an array and return an array of deleted elements. It takes as arguments the starting index, the number of elements to remove, and optionally the element to add.

      Usage example:

      const arr = [1, 2, 3, 4, 5];
      const deletedElements = arr.splice(2, 2); // delete 2 elements starting from index 2
      console.log(arr); // output: [1, 2, 5]
      console.log(deletedElements); // output: [3, 4]
      
      arr.splice(1, 0, "a", "b"); // do not remove elements from index 1, add "a" and "b"
      console.log(arr); // output: [1, "a", "b", 2, 5]
      

These methods are very commonly used in the processing of strings and arrays. They can be used to split and connect strings, slice, add and delete arrays according to specific needs.

What is split()? What is its function? How to use it?

split() is a JavaScript string splitting method, its function is to split a string according to the specified delimiter, and return an array composed of the split substrings.

The usage format of the spit() method is:

string.split(separator, limit);

Among them, string is the original string to be split; separator is the delimiter, which can be a fixed string or a regular expression; limit is an optional parameter used to limit the number of returned substrings.

For example, suppose you have the following strings:

var str = "JavaScript is a powerful programming language.";

If we want to separate the string based on spaces, we can use the following code:

var arr = str.split(" ");
console. log(arr);

After execution, the following results will be output:

["JavaScript", "is", "a", "powerful", "programming", "language."]

Here arr is an array containing the divided substrings.

It should be noted that the split() method does not modify the original string, but returns a new array.

What is join()? What is its function? How to use it?

join() is an array method in JavaScript. Its function is to convert all elements of the array into strings and connect them using the specified separator.

Its syntax is as follows:

array. join(separator)

Among them, ARRAY is the array to be connected, separator is an optional separator, and the default is a comma. The function returns a string containing all array elements.

Give an example to illustrate its usage and function:

var fruits = ["apple", "banana", "orange"];
var result = fruits.join(); // The result is: apples, bananas, oranges

In this example, we have an array called fruits that contains the names of three fruits. The join() function is called without any parameters, so the default delimiter is a comma. As a result, the elements in the array will be connected with commas to get a string: “apples, bananas, oranges”.

You can also customize the delimiter, for example:

var numbers = [1, 2, 3, 4];
var result = numbers.join("-"); // The result is: 1-2-3-4

In this example, we set the parameter of the join() function as a horizontal line (“-“), and as a result, the elements in the array will be connected with a horizontal line to get a string: “1-2-3- 4”.

It should be noted that the join() function will automatically convert each element in the array to a string. If an element in the array is NULL or UNDEFINED, it will be converted to an empty string.

To sum up, the role of the join() function is to connect the elements of the array to form a string, and you can customize the separator. It is very useful, especially when you need to output the contents of the array in a specific format.

There is another syntax:

JSON.stringify(value[, replacer[, space]])

Among them, value is the JavaScript object to be converted, replacer is an optional parameter used to control which attributes should be included in the final string, and space is also an optional parameter used to define the indentation of the output string.

Here are some examples:

var person = {
  name: "John",
  age: 30,
  city: "New York"
};

var jsonString = JSON. stringify(person);
console.log(jsonString);
// The result is: {"name":"John","age":30,"city":"New York"}

In this example, we have an object named person. By calling the JSON.stringify() function and passing in person as an argument, it will convert the object into a string in the following format: {"name\ ":"John","age":30,"city":"New York"}.

It should be noted that the JOIN.stringify() method will only include the enumerable properties of the object in the final string. If you want to further filter, replace or perform other operations on the attributes to be included, you can use the replacer parameter. This parameter can be a function or an array.

In addition, the space parameter is used to specify the indentation length when outputting strings. If this parameter is not specified, the resulting string will not have any indentation.

var person = {
  name: "John",
  age: 30,
  city: "New York"
};

var jsonString = JSON. stringify(person, null, 2);
console.log(jsonString);
// The result is:
// {
// "name": "John",
// "age": 30,
// "city": "New York"
// }

In the example above, we passed in null as an alternative (since we don’t need to do property substitution) and set the space parameter to 2, so that the output characters Strings are indented with 2 spaces.

To summarize, the JOIN.stringify() method is used to convert JavaScript objects into strings, making them suitable for network transmission or storage. It is one of the common ways of working with data, especially for exchanging data with a server, as well as saving data in local storage or in a browser session.

What is slice()? What is its function? How to use it?

slice() is a method in JavaScript and has similar functionality in Python and some other programming languages. It is used to extract the specified range of elements from an array or string and return a new array or string without changing the original array or string.

The slice() method has two parameters: start and end. start indicates the starting position to be extracted (including the element at this position), and end indicates the end position to be extracted (excluding the element at this position). If the end parameter is omitted, the default is to extract to the end of the array or string.

Here is an example using the slice() method:

var arr = [1, 2, 3, 4, 5];
var slicedArr = arr.slice(1, 4); // from index 1 up to index 4 (not including 4)
console.log(slicedArr); // output [2, 3, 4]

var str = "Hello World";
var slicedStr = str.slice(6); // Extract from index 6 to the end of the string
console.log(slicedStr); // output "World"

It should be noted that the slice() method does not modify the original array or string, but returns a new slice.

What is splice()? What does it do? How to use it?

splice() is a method in JavaScript and has similar functionality in Python and some other programming languages. It is used to mutate the original array or string, elements can be deleted, inserted and replaced.

The splice() method has three parameters: start, deleteCount and items. start indicates the index of the starting position to be modified, deleteCount indicates the number of elements to be deleted, and items is an optional parameter indicating the new elements to be added to the array or string.

Here is an example using the splice() method:

var arr = [1, 2, 3, 4, 5];
arr.splice(2, 2); // delete 2 elements starting from index 2
console.log(arr); // output [1, 2, 5]

var str = "Hello World";
var newStr = str.splice(6, 0, ","); // insert comma at index 6
console.log(str); // output "Hello, World"

It should be noted that the splice() method directly modifies the original array or string and returns an array containing the deleted elements, or an empty array if no elements are deleted. When we insert new elements into the original array or string, the splice() method returns an empty array.