Strings Skills Test 2
Hi! I am working on #2. I am getting the desired result with the following code but I don’t think it’s “correct.” Your feedback would be greatly appreciated!
let quoteLength = quote.length;
let index = quote.indexOf(substring);
let revisedQuote = quote.slice(0,33);
Hiya @Tess_Bishop! You are definitely on the right track here; your example works fine. However, I suppose you are concerned that your usage of slice()
is kind of a brute force approach, just using the raw number to slice up to rather than working it out?
Something like the following would be more flexible, and would work for any string and substring:
let revisedQuote = quote.slice(0, index + substring.length + 1);
Basically, to get the end of the place where you want to slice up to, add the index (the start of substring), plus the substring length, and then add 1 to get the full stop too.
4 Likes
Thank you @chrisdavidmills ! I don’t full understand how + 1 gets me the full stop. Where can I learn more about this?
@Tess_Bishop it is all to do with the index positions of the characters in the original string. Let’s go through it step by step.
- The string’s first character is at index number 0 — computers count from 0, not 1.
- The substring’s first character appears at index number 14. This is what
quote.indexOf(substring)
returns.
- adding the substring’s length to that (18), will get us to the end index position of the substring — 32. If we did
quote.slice(0, index + substring.length);
, we’d get the string sliced up to the end of the substring, but not including the full stop.
- To get the full stop as well, we need to add 1, hence we end up with
quote.slice(0, index + substring.length + 1);
5 Likes
Is it normal to feel completely dumbfounded by your solution? I came up with the same as OPs, and had no understanding in doing what you did.
Say it wanted the following quote: “I do not like green eggs and ham. I do not like them”. How would I set it up using your method? It kinda feels like cheating using a number bigger than 1 at the end.
Hi @Leonardo_Nobre_Ghiggino it is fairly common to feel confused when you start learning a programming language — programming is by it’s nature a complex and diffcult thing to learn, so you just need to keep practising, until it becomes clearer.
As for your example — I do not like green eggs and ham. I do not like them
— if you wanted to end up with this revised quote, you’d probably use a different approach wth a different substring, but it’d be pretty similar. It’s just a trivial example to get you started off with manipulating strings.
1 Like
Thank you so much, David! You always can explain everything clearly!
And for anyone who found it difficult to understand, it’s okay because it’s not our natural language. Just keep learning, read the documentation, and don’t forget to keep practicing. Please, don’t ever give up because once you understand it, you’ll get the satisfaction.
1 Like