I am working through the chapters and exercises for A Smarter Way to Learning JavaScript, Chapter 23 covers Strings: Finding Segments using indexOf and lastIndexOf methods.
In the example a second variable firstChar is assigned the value of a variable text which contains a string "World War II". The objective is to replace the string "World War II" with a new string "the Second World War". The following code accomplishes the task, however I don't understand how line 3 works. I understand that indexOf will return the value of the first occurrence of the segment in this case 0, but I don't know how it's removing "World War II". My question is how is line 3 working?
0 var text = "World War II";
1 var firstChar = text.indexOf("World War II");
2 if (firstChar !== -1) {
3 text = text.slice(0, firstChar) + "the Second World War" + text.slice(firstChar + 12);
4 {
slice(start, end) is used to take a substring from the specified starting index to the ending index.
So,
text.slice(0, firstChar)
will return a substring from start=0 to end=0 because the value of firstChar is 0.(this returns empty string)Now, the string the "Second World War" will be added to null making the value of
text = the Second World War
slice(start) with a single parameter return the string starting from "start" uptil the end of the string.
For this example we get the same result even without writing
text.slice(firstChar + 12)
because firstChar + 12 = 0 + 12 = 12, but the total length of original string "World War II" is 12 and hence we will get an empty string.But suppose the initial value of "text" would have been
text = "World War II was deadly"
i.e. if there is some text after the string we want to replace viz. "World War II" then the linetext.slice(firstChar + 12)
appends the remaining portion of the string which in this case is "was deadly" and the value of text becomes,