100

This may duplicate with previous topics but I can't find what I really need.

I want to get a first three characters of a string. For example:

var str = '012123';
console.info(str.substring(0,3));  //012

I want the output of this string '012' but I don't want to use subString or something similar to it because I need to use the original string for appending more characters '45'. With substring it will output 01245 but what I need is 01212345.

Jack Steam
  • 4,500
  • 1
  • 24
  • 39
Phon Soyang
  • 1,303
  • 2
  • 9
  • 17
  • 5
    In this case, when it's a string, you'd be getting the characters, not necessarily digits. But I'm confused - you *are* getting the first 3 characters of the string. So what are you trying to do? – elzi Oct 06 '16 at 02:52
  • Strings are immutable. – PM 77-1 Oct 06 '16 at 02:52
  • 4
    `substring` will return a new string `012`, but `str` will still be equal to `012123`. `substring` will not change the contents of `str`. – Dave Cousineau Oct 06 '16 at 02:52
  • 2
    Please [edit] your question to show how you are trying to use the results. Calling `.substring()` (or `.slice()` or `.substr()`) doesn't change the original string at all, it returns a *new* string. `str` doesn't change unless you explicitly overwrite it with `str = str.substring(0,3)`. – nnnnnn Oct 06 '16 at 02:52
  • 2
    The above commenters are correct-- the method just returns what you want without changing the original string. So you can store the returned value in a variable like `strFirstThree = str.substring(0,3)` and still have access to `str` in its entirety. – Alexander Nied Oct 06 '16 at 02:54

2 Answers2

170

var str = '012123';
var strFirstThree = str.substring(0,3);

console.log(str); //shows '012123'
console.log(strFirstThree); // shows '012'

Now you have access to both.

Flimm
  • 136,138
  • 45
  • 251
  • 267
Alexander Nied
  • 12,804
  • 4
  • 25
  • 45
27

slice(begin, end) works on strings, as well as arrays. It returns a string representing the substring of the original string, from begin to end (end not included) where begin and end represent the index of characters in that string.

const string = "0123456789";
console.log(string.slice(0, 2)); // "01"
console.log(string.slice(0, 8)); // "01234567"
console.log(string.slice(3, 7)); // "3456"

See also:

Flimm
  • 136,138
  • 45
  • 251
  • 267
  • 1
    And if you omit the `end` then it will give you back the rest of the string from the `start`. With `string` from above: `console.log(string.slice(7)); // "789"` – wkille Jan 21 '23 at 18:54