In JavaScript, you can use the substring
method to extract a portion of a string. The substring
method takes two arguments: the start index and the end index. The portion of the string that is returned includes the character at the start index and goes up to, but does not include, the character at the end index.
Here’s an example:
const message = 'Hello, World!';
const greeting = message.substring(0, 5);
console.log(greeting); // Output: Hello
In this example, the substring
method is used to extract the first five characters of the string message
, which is 'Hello'
.
You can also use the slice
method to extract a portion of a string in JavaScript. The slice
method works similarly to substring
, but it also allows you to specify negative indices, which count from the end of the string.
Here’s an example:
const message = 'Hello, World!';
const greeting = message.slice(0, 5);
console.log(greeting); // Output: Hello
const farewell = message.slice(-6, -1);
console.log(farewell); // Output: World
In this example, the slice
method is used to extract both the first five characters of the string message
and the last five characters of the string message
.
+ There are no comments
Add yours