Array Methods to Manipulate Strings
Explore key JavaScript array methods such as concat, slice, and splice to manipulate strings. Understand how these methods create new arrays, extract sections, and modify array contents, enabling you to handle string data efficiently in front-end development.
Arrays have a number of methods that can be used to manipulate existing arrays.
The concat() and slice() methods
The Listing below demonstrates two of them, concat(), and slice().
Listing: Exercise/index.html
<!DOCTYPE html>
<html>
<head>
<title>Concat and slice</title>
<script>
var fruits = ["apple", "banana"];
var fruit2 = fruits.concat(["orange", "lemon"],
"pear");
console.log(fruit2.toString());
var fruit3 = fruit2.slice(2, 4);
console.log(fruit3.toString());
</script>
</head>
<body>
Listing 7-18: View the console output
</body>
</html>This code snippet produces this output:
The concat() method returns a new array comprised of this array joined with other arrays and values. In this listing, fruit2 is assembled from the original contents of fruits and from the items in the ["orange", "lemon"] array, plus “pear,” as shown in the ...