span and a text node. The idea was to get the contents of the
span, and the rest of the text in two separate variables. My first instinct was to grab the contents of the
span, and then grab the contents of the text node that followed the
span, but I discovered that there were actually two different text nodes. One was empty, and the other one had the text I wanted to get. Since this is an action that needs to be repeated a number of times and there is no guarantee that there will always be two different text nodes, I decided to just grab the content of the
span, and then the full
textContent of the parent element, and just remove the text in the spam from the full text.
When the time came to remove the contents of the
span from the full text, I decided to use the
slice method of
String. This method takes a starting offset, and an ending offset. So, if I have the text “Hello”, and I
slice starting at index 1, I would get back “ello”. In my particular case, the full text starts with a code, and then a description. For example, “ABC Some description”. The idea is to get a variable with the value “ABC”, and another one with the value “Some description”. So, all I had to do was slice the full string starting at the index equivalent to the length of the code string, which is what is contained in the
span element. But if you pay attention, you will realize a small problem: I would end up with the value ” Some description”. Notice the leading space at the start of the string.
At this point, many programmers would just call
slice with the starting index set to the length of the code string plus 1. This gets the job done, but later in the future you, or some other programmer who inherits your code may wonder why you added 1 to the length of the code string used as the starting offset. Some programmers will tell you that that is what comments are: to provide clarification on situations like this one. But I’m recently of the idea that comments in code are often just noise. And yes, I know this goes against most advise you’ve heard around. I’m not saying comments are bad, I’m saying if your code needs comments, your code is probably bad. And by “bad” I mean, not expressive enough.
It turns out there is a better solution for this: use
trim(). The trim method is very expressive. It tells you “Hey, this string may or may not have leading or trailing spaces that I don’t want, so I will remove them”. Yes, it says all that in just 4 characters…
The point is, if you need to write a comment in your code, pause for a second and think “Is there a way to say in code what I’m trying to say in comment?”