Is String.substr() giving back the complete string?

Currently, I am working on an application that transforms lyrics into Google Slides by analyzing the number of line breaks between stanzas. To simplify the process, I have been repeatedly testing a specific set of lyrics. The procedure involves locating the position of the word 'foo' within the text and extracting a substring starting from the beginning up to that index in order to store it in an array. This array will later be utilized in generating slides through another function.

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;
}

The expected outcome is to log "Original lyrics blah blah", followed by the index number, and then display the extracted substring such as "blah blah". However, the actual output logs "Original lyrics blah blah" first, then the index number, and finally repeats with "Original lyrics blah blah".

Answer №1

The key solution to your dilemma revolves around the single use of = in your equality comparison within the conditional statement. This is inadvertently assigning the value of lengthOfChunk to -1, resulting in a scenario where lyrics.substr(0) yields the entire string.

To overcome this issue, consider employing lyrics.split("[your word]") as an alternative approach instead of manually populating an array and iterating through strings within a while loop. Assuming I have correctly interpreted the problem at hand, you could simply implement:

splitLyrics = lyrics.split("foo");

By doing so, you will obtain an array comprising all substrings excluding the specified keyword.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Remove all $.ajax requests from content that has been loaded using $.ajax in jQuery

I'm currently working on a page where users can click a link to load content using $.ajax into a designated container div. However, I've encountered an issue with multiple clicks causing an increase in the number of $.ajax requests and resulting ...

Connecting via web sockets through SSL is not functioning properly

My Web Socket functions correctly in both the localhost and production environments (https://www.example.com). However, upon deploying the same code to the pp environment (), I encounter the error message: WebSocket handshake - Unexpected response code: 4 ...

Sending information from a Bootstrap modal form

I'm experiencing an issue with my form that triggers a modal for confirmation before submission. The modal contains the submit button and is located outside of the <form> tag. Surprisingly, it works perfectly fine on all browsers except for Inte ...

What is the best way to organize and structure a node.js project for modularity?

In the process of developing a node.js project, I am adhering to the class constructor pattern as shown below: function my_class(x,y){ this.x = x; this.y = y; } The foundation of the project lies within the main.js file. It is imperative that any ...

Issue: The module "node:util" could not be located while attempting to utilize the "sharp" tool

Upon adding sharp to my Node.js application and attempting to use it, I encountered the following error: /Users/username/Documents/GitHub/Synto-BE/node_modules/sharp/lib/constructor.js:1 Error: Cannot find module 'node:util' Require stack: - /Use ...

Having trouble with your Ajax JQuery request?

I am currently attempting to create a basic AJAX request to the URL provided below: When I enter the URL directly into the browser's navigation bar and press enter, I receive the JSON response. However, when attempting to make a jQuery AJAX call, it ...

Successfully Determining User Identity with Ajax Authentication

Currently, I am facing a security issue with my login page that uses an Ajax request for user authentication. The password entered by the user is sent as plain text in the form data of the Ajax request, making it vulnerable to interception by sniffing tool ...

Tips for leveraging _.union function from lodash to eliminate duplicate elements from several arrays in a TypeScript project

I attempted to use import _ from 'lodash-es' and _.union(user.users.map(user => user.city)). However, the result was not as expected, such as: ["city_id1", "city_id2", "city_id3", "city_id4"] What is th ...

Creating a service function (constructor) in JavaScript

When working with AngularJs and calling a service method: app.service('nameService', function() { this.Service = function (){console.log('hello')} } You can then use this service (object) like so: nameService.Service() My question is, ...

Step-by-step guide on loading Maya exported .FBX files into Babylon JS

Is it possible to import .fbx files in Babylon.js like Three.js does? If so, what is the process for doing that? I've seen some suggestions online about converting .fbx files to .babylon or using Unity/3DS Max to convert them. However, this seems like ...

Scroll the table automatically when the currently selected row is the second-to-last row

Having trouble with a scrolling table issue. https://i.sstatic.net/PFyN3.png Upon page load, the first row (ROW 1) is automatically selected and highlighted. Clicking the next button selects and highlights the subsequent rows. However, once ROW >= 8 (e ...

The function is not explicitly declared within the instance, yet it is being cited during the rendering process in a .vue

import PageNav from '@/components/PageNav.vue'; import PageFooter from '@/components/PageFooter.vue'; export default { name: 'Groups', components: { PageNav, PageFooter, }, data() { return { groups: ...

What is the best way to modify the ID of a duplicated element?

I have been working on creating a drag and drop editor using react-smooth-dnd. The setup involves two containers: a toolbar with elements and an editor where the elements can be dragged and dropped. Each element in the toolbar has the following structure: ...

How to direct all wildcard paths to a particular route in Next.js

I currently have a single landing page application built with nextJs. I am wondering if it is possible to redirect all paths to specific routes, similar to how we do it in react-router. How can I achieve the same functionality in nextJs? <BrowserRou ...

Is there a simple solution to show script 1 to visitors from the US and Canada, while displaying script 2 to visitors from other countries?

I'm looking for a simple script that can show one script to visitors from the US and Canada, and another script to visitors from other countries. It doesn't have to be perfect, but using a service like seems too complex for me. Is there a stra ...

Check for pattern using JavaScript regular expression

Utilizing ng-pattern to validate a regular expression. The pattern must include 3 letters and 2 numbers in a group. For example: G-31SSD or G-EEE43 Currently, the pattern only matches the second example. ng-model="newGroup.groupCode" ng-pattern="/^&bso ...

The problem with the first item title in the Jquery slider is causing

I've been working on setting up a Jquery slider (caroufredsel) in which I want certain elements to be displayed above the slider itself, outside of the wrapper. Everything is working fine except for the first slide! After spending several days trying ...

Display outcome generated by JavaScript in the input box

I've successfully implemented a date/time picker in a form. Using JavaScript, I've created a script to calculate the difference between two date fields and display it in a third field labeled Course Duration. However, I'm encountering an i ...

Ways to retrieve a variable within the init() function

My current project involves using datatables along with ajax to display information dynamically. Below is the code snippet I am working with: // Setting up the module var DatatableAdvanced = function() { // Examples of Basic Datatables var _c ...

tips for implementing JSON loading in Ext JS

While attempting to load values from a web service, I encountered the following error message: "ChatStore.data.items[i] is undefined." The mapping code for extjs is as follows: ChatStore = new Ext.data.JsonStore({ storeId: 'ChatStore1' ...