# The substr method

The `substr` method returns a substring from a string (the original string is not changed). The first parameter specifies the position number from which the method will start cutting (numbering starts from zero), and the second parameter - how many characters to cut.

The first parameter can take negative values. In this case, the character from which the cutting begins will be counted from the end of the string. The last character is numbered `-1`. The second parameter is optional, if it is not specified, then all characters up to the end of the string will be cut.

## Syntax

`string.substr(where to start, [how many characters to cut]);`

## Example

Let a string be given. Let's cut out the first `3` characters from it:

`let str = 'abcde'; let sub = str.substr(0, 3); console.log(sub);`

The code execution result:

`'abc'`

## Example

Let's now cut the characters from the `2`nd position to the end of a string (for this, we will not set the second parameter of the method):

`let str = 'abcde'; let sub = str.substr(2); console.log(sub);`

The code execution result:

`'cde'`

## Example

Let's cut the substring from the `3`rd character from the end and take `2` characters:

`let str = 'abcde'; let sub = str.substr(-3, 2); console.log(sub);`

The code execution result:

`'cd'`

## Example

And now let's cut the substring from the `3`rd character from the end and take the entire remaining string (for this we will not set the second parameter of the method):

`let str = 'abcde'; let sub = str.substr(-3); console.log(sub);`

The code execution result:

`'cde'`

## Example

Let's cut the last character of a string:

`let str = 'abcde'; let sub = str.substr(-1); console.log(sub);`

The code execution result:

`'e'`

## See also

- the `substring` and `slice` methods
  that also return a substring

← →
↑
en ru