Search code examples
javascriptgoogle-apps-scriptsubstr

String.substr() returning entire string?


I'm writing an application that takes lyrics and formats them into Google Slides based on number of line breaks between stanzas. To keep the logic simple, I've been testing the same set of lyrics and finding the index of the word 'foo' and using that index to create a substring to push into an array. This array will be used to make slides in another function.

When I try to use the index of the word to do lyrics.substr(0, index), it returns the entire string, even with a valid index number.

function splitLyrics(lyrics) {
  var lyricsArray = []; 
  var lengthOfChunk = 0;
  var lengthOfSong = 0;
  var lyricsToPush;

  while (lyrics.length > 0) {
    Logger.log(lyrics);
    lengthOfSong = lyrics.length;
    lengthOfChunk = lyrics.indexOf('foo');
    Logger.log(lengthOfChunk);

    if (lengthOfChunk = -1) {
      lengthOfChunk = lengthOfSong;
    }

    lyricsToPush = lyrics.substr(0, lengthOfChunk);
    Logger.log(lyricsToPush);
    lyricsArray.push(lyricsToPush);

    lyrics = lyrics.substr(lengthOfChunk + 1);
  }

  return lyricsArray;
}

I expect the outputs of the logs to be "Original lyrics blah blah", the index number, and then "blah blah" or whatever substring output. Instead I get "Original lyrics blah blah", the index number, and then "Original lyrics blah blah"


Solution

  • A specific answer to your situation lies in the single = used for your equality check in the if statement. It is actually setting the value of lengthOfChunk to -1, meaning it is taking a lyrics.substr(0) which returns the full string.

    However, it sounds like you can use lyrics.split("[your word]") instead of having to manually populate the array and move to the next string within the while loop. If I read the problem correctly, you could just:

    splitLyrics = lyrics.split("foo");
    

    This will get you an array of all strings not including the keyword.