😄 This post is based on the content from coding.courses.
Definition and Usage
The slice() function for strings slices a string by a specified index range and returns a new string.
Using this function, you can easily slice and extract a string within the desired range.
Features
- The string sliced by the specified index range is returned as a new string.
- The index range is determined by the start and end parameters you specify (the end index is not included).
- With this behavior, the original string remains unchanged.
Basic Example
/**
* A function that slices a specific range of a string
* and returns the result as a new string.
*
* str.slice(beginIndex[, endIndex])
*
* @param {number} beginIndex - The starting index of the substring to extract.
* @param {number} endIndex - The ending index of the substring to extract (not included).
* @returns {string} - The extracted substring.
*/
/*
* Note:
* In strings, indexes start at 0.
* The first character has an index of 0, and the second character has an index of 1.
*/
const greeting = "Welcome. This is codingCourses.";
const welcome = greeting.slice(0, 7);
console.log(welcome); // Output: "Welcome"
const courseName = greeting.slice(17, 31);
console.log(courseName); // Output: "codingCourses"
/* 👇 The original string remains unchanged. */
console.log(greeting); // Output: "Welcome. This is codingCourses."
Syntax
str.slice(beginIndex[, endIndex])
str is the string to which the slice() function is applied.
Parameters
# beginIndex
- If omitted, the default value is 0.
- If omitted, the default value is 0.
- Negative values can be used, counting backward from the end of the string.
- If greater than or equal to the length of the string (str.length), no characters are extracted.
# endIndex
- Optional. Specifies the index at which to end extraction.
- slice() extracts characters up to, but not including this endIndex index.
- If omitted, extraction continues to the end of the string.
- Negative values can be used, counting backward from the end of the string.
- If greater than or equal to the length of the string (str.length), extraction continues to the end of the string.
Return Value
The slice() function for strings extracts characters from the original string within the specified index range and returns them as a new string. The returned string is a copy of the selected characters, so the original string remains unchanged.
# Parameter and Return Value Examples
let str1 = "Welcome!", // The length of str1 is 8
str2 = str1.slice(1, 8),
str3 = str1.slice(4, -1),
str4 = str1.slice(),
str5 = str1.slice(30);
console.log(str2); // Output: "elcome!"
console.log(str3); // Output: "ome"
console.log(str4); // Output: "Welcome!"
console.log(str5); // Output: ""
Top comments (0)