Extracting a section of a string and returns it as a new string in JavaScript : slice()

Java Script @ Freshers.in

This article provides an in-depth look at the slice() method, complete with executable examples, ensuring you can understand and use this functionality effectively in your coding endeavors.

Understanding String’s slice():

The slice() method extracts a section of a string and returns it as a new string, without modifying the original string. It selects the elements starting at the provided start index and ends at, but does not include, the provided end index.

Syntax:

The syntax for the slice() method is quite straightforward:

string.slice(startIndex, endIndex)
  • startIndex: The zero-based index at which to begin extraction. If negative, it’s treated as strLength + startIndex where strLength is the length of the string (for example, if startIndex is -3 it is treated as strLength – 3).
  • endIndex: Optional. The zero-based index before which to end extraction. The character at this index will not be included. If endIndex is omitted, slice() extracts to the end of the string. If negative, it is treated as strLength + endIndex.

Examples and Execution: Below are practical examples demonstrating the use of the slice() method in various scenarios. You can execute these examples in any JavaScript environment, such as a browser’s developer console or Node.js.

Basic usage:

let str = "Hello, World!";
let newStr = str.slice(7);
console.log(newStr); // Outputs: "World!"

Using negative indices

let str = "JavaScript";
let newStr = str.slice(-6, -1);
console.log(newStr); // Outputs: "Scrip"

No modifications on original atring:

let originalStr = "Immutable";
let newStr = originalStr.slice(2, 6);
console.log(newStr); // Outputs: "muta"
console.log(originalStr); // Outputs: "Immutable" (original string remains unchanged)

Omitting the endIndex:

let str = "Hello, World!";
let newStr = str.slice(7);
console.log(newStr); // Outputs: "World!" (extracts to the end of the string)

Function to extract substring:

function extractSubString(originalString, start, end) {
    return originalString.slice(start, end);
}

let myString = "Learning JavaScript is fun!";
let mySubString = extractSubString(myString, 9, 19);
console.log(mySubString); // Outputs: "JavaScript"

The slice() method is a versatile and powerful feature in JavaScript for string manipulation, allowing developers to easily extract portions of a string based on specified indices. It offers the flexibility of using both positive and negative indices, granting more control over the slicing process.

Get more articles on Java Script

Read more on Shell and Linux related articles

Refer more on python here :

Author: user