Useful string methods, Making new Strings from old parts

Hello,

I just finished working through Making new Strings from old parts and I would like help understanding the let name = input.slice(semiC + 1); part of the code.

for (let i = 0; i < stations.length; i++) {
let input = stations[i];
let code = input.slice(0,3);
let semiC = input.indexOf(’;’);
let name = input.slice(semiC + 1);
let result = code + ‘:’ + name;

Initially I thought let name = input.slice(semiC ); without the +1 was sufficient, given the following statement:

“…if you know that you want to extract all of the remaining characters in a string after a certain character, you don’t have to include the second parameter! Instead, you only need to include the character position from where you want to extract the remaining characters in a string.”

Specifically what is +1 referring to?

Thank you!

So, to understand this a bit better, try running the example with semiC instead of semiC + 1 — you end up with the semi-colons stuck on the front of the names.

So we are adding 1 to the slice value to make the slice happen after the semi-colon, not before it, leaving us with just the names.

This happens in the first place because indexOf returns the index position of the character, but slice counts from the beginning of the string, and remember that computers count from 0, not 1. This is why this is giving you a slice one position further to the left than we were expecting, hence us needing the +1.

Does that help?

Thank you @chrisdavidmills!

I ran the

let name = input.slice(semiC + 1);
let result = code + ‘ ; ’ + name;

part of the code with semiC only, as well as with code + name only.

While semiC +1 intentionally leaves out the semi-colon, let result = code + ‘ ; ’ + name; adds it back in with additional space around it.