Home
Node.js
Substring Examples
Updated Dec 13, 2023
Dot Net Perls
Substring. A string has 10 characters, but we wantonly a part of this string—the first 5, the last 3. With substring we get a string from within an existing string.
In Node.js, substring receives 2 arguments: the first index of the substring we are trying to take, and the last index. The second argument is not a count.
First example. Let us begin with this example. We have an input string "cat123." To get the "cat" part, we use a first index of 0, and a last index of 3.
Argument 1 The index of the first char we are taking a substring at—the first char in a string is at index 0.
Argument 2 The last index of the substring. This is not a count, but rather another position in the string.
var value = "cat123"; console.log("VALUE: " + value); // Take a substring of the first 3 characters. // ... Start at index 0. // ... Continue until index 3. var result = value.substring(0, 3); console.log("SUBSTRING: " + result);
VALUE: cat123 SUBSTRING: cat
Substring, 1 argument. Substring can be used with just 1 argument. This is the start index. We can think of this argument as the number of characters we want to skip over.
Info For substring with 1 argument, the remaining part of the string (after the index specified) is included.
var value = "x_frog"; // Skip over first 2 characters. var result = value.substring(2); console.log("VALUE: " + value); console.log("SUBSTRING: " + result);
VALUE: x_frog SUBSTRING: frog
With substring, we have a way to extract parts of strings. For optimal performance, using the original string and not changing it at all is best, but this is not always possible.
Dot Net Perls is a collection of pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 13, 2023 (edit).
Home
Changes
© 2007-2025 Sam Allen