Useful string methods query


(Modestas) #1

Hi guys i’ve just completed the third challenge in the “useful string methods” section but i have a question.

var list = document.querySelector(’.output ul’);
list.innerHTML = ‘’;
var stations = [‘MAN675847583748sjt567654;Manchester Piccadilly’,
‘GNF576746573fhdg4737dh4;Greenfield’,
‘LIV5hg65hd737456236dch46dg4;Liverpool Lime Street’,
‘SYB4f65hf75f736463;Stalybridge’,
‘HUD5767ghtyfyr4536dh45dg45dg3;Huddersfield’];

for(var i = 0; i < stations.length; i++) {
var input = stations[i];
var code = input.slice(0,3);
var semiC = input.indexOf(’;’);
var name = input.slice(semiC + 1);
var final = code + ': ’ + name;
var result = final;
var listItem = document.createElement(‘li’);
listItem.textContent = result;
list.appendChild(listItem);
}

why in the above code do i need to first store input.indexOf(’;’); in the variable semiC before i can slice the string starting from the semicolon? Theoretically, shouldnt you just be able to use
var name = input.slice(";" + 1); which saves the need to store the semi colon in a variable? Or is it because the slice method is not allowed to take strings as parameters? thanks!


(Chris Mills) #2

Hi there!

It is done this way because input.indexOf(’;’) is finding the index number of the semi-colon (i.e. its position) in the main string in each case. So for example, when applied to “SYB4f65hf75f736463;Stalybridge”, input.indexOf(’;’) would return 19, as the ; is the 19th character.

var name = input.slice(semiC + 1); then slices the string just after the specified index position, and stores it in the name variable. The specified index position is always semiC + 1, which gives us everything after the semi colon — we just want to extract the station name.

If you passed in the ; directly to the slice method it would error, as yes, it only takes an index number as a parameter (in its most basic form).