Display the input text line by line

How can I achieve the desired output for this input parameter?

  displayText("you and me");
  expected output:
  ["you and me", "you and", "and me", "you", "and", "me"]

I have attempted to solve it using the following code, but the results are incorrect. Here is my current code:

 let displayText = (txt) => {
   let output= []
   for(let i = 0; i < txt.length; i++) {
       for(j = i + 1; j < txt.length + 1; j++) {
          output.push(txt.slice(i, j))
       }
   }
   return output
}

Answer โ„–1

To start, begin by breaking down the sentence into individual parts:

const sentence = 'she and I'
const words = sentence.split(' ')

The challenging aspect is extracting the elements in pairs. Utilize slice to accomplish this:

   const pairCount = words.length - 1
   for (let i=0; i<pairCount ; i++) {
      console.log(words.slice(i, i+2).join(' '))
   }

Next, display each individual word:

  words.forEach(word => console.log(word))

Answer โ„–2

To begin, the sentence should be divided into parts: For instance:

let strArray = myString.split(" ");
let finalOutput= []    
let tempString = "";
 for (let i = 0; i < strArray.length; i++) {
        tempString = strArray[i];        
        finalOutput.push(tempString)
            for (let j = i + 1; j < strArray.length; j++) {
                tempString += strArray[j];
                finalOutput.push(tempString)
            }
    }
    console.log(finalOutput)

This is one approach you could take.

Answer โ„–3

For your function to work as intended, make sure to split the string on word breaks and declare the variable j.

let displayText = (txt) => {
  txt = txt.split(' ');
  
  let output = []
  for (let i = 0; i < txt.length; i++) {
    for (let j = i + 1; j < txt.length + 1; j++) {
      output.push(txt.slice(i, j).join(' '))
    }
  }
  
  return output
}

console.log(displayText("you and me"))

If you want to return an array sorted by combination length, consider grouping each slice by word count and using the flat() method on the output array before returning.

let displayText = (txt) => {
  txt = txt.split(' ');

  let
    len = txt.length, output = [];
  for (let i = 0; i < len; i++) {
    for (let j = i + 1; j < len + 1; j++) {
      (output[len - (j - i)] ??= []).push(txt.slice(i, j).join(' '))
    }
  }
  // before flat() call
  // [ [ 'you and me' ], [ 'you and', 'and me' ], [ 'you', 'and', 'me' ] ]
  return output.flat()
}

console.log(displayText("you and me")); 

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

Translating coordinates into their corresponding location on the chart

I'm currently working with a dataset containing information about an area in Western Europe. I am trying to convert coordinates into values within this table, facing a challenge similar to the one described in this query. However, I lack experience in ...

Setting header details for optimal data transfer

Currently, there is a Java code snippet that I am working on which attempts to access the header information sent by an HTML page. Unfortunately, I do not currently have the specific HTML page in question. However, I still need to be able to access and m ...

Could using 'require' in node.js lead to a memory leak issue?

I have been working on a program that experiences continuous heap growth. The program is quite simple - it repeatedly tries to load an external file (SyntaxError) using require. However, this external module fails to load due to a syntax error present in i ...

Discovering the art of interpreting the triumphant outcome of an Ajax request with jquery/javascript

I recently encountered a challenge with my function that deals with a short JSON string: <script id="local" type="text/javascript"> $( document ).ready(function() { $('tr').on('blur', 'td[contenteditable]', functi ...

Using jQuery to create transitions when a class is changed and adding a delay to the transition

If you want to check out the section I created on CodePen, feel free to visit it by clicking here. I've noticed that my JavaScript code has a lot of repetitive elements and I'm looking to optimize it for better performance. Any advice on how I c ...

Having difficulty with a script not functioning properly within an onclick button

In my script, I am using the following code: for (var i in $scope.hulls) { if ($scope.hulls[i].id == 1234) { console.log($scope.hulls[i]); $scope.selectedHullShip1 = $scope.hulls[i]; } } The code works fine outside of the onclick button, but fails to run ...

Best method for reverting react-native to previous version

Here's the dilemma I'm facing: I had a functional version of a react-native project that was running smoothly and committed to my git repository. Deciding to upgrade from react-native 0.26.3 to 0.28 led me into a tangled web of dependencies, so ...

Is there a way to utilize ajax to submit a form and upload a file to a spring controller?

I have a form with four fields: file, name, type (as a string), and taskInstanceId. <form> <table id="documentDetailsTable"> <tr> <td>Document Type: </td> <td><select id="documentType" ...

The image is loaded correctly through the image picker, however, it is not displaying on the screen

When I click the button to pick an image from the gallery in this code, it is supposed to load the phone's gallery and display the selected image in the image component. Even though the image gets loaded properly (confirmed through test logs), it does ...

Adding a MTL texture to an OBJ in your three.js project is a simple process that can enhance

Hello! I am currently working on adding an MTL file to my OBJ in three.js. I had successfully loaded my OBJ and went back to address this issue. However, after adding the code to load the MTL file using MTLLoader, the code seems to be getting stuck at mt ...

Behat automates the process of populating form fields that are dynamically displayed as 'visible'

I'm facing an issue with a form that has hidden fields. When a user selects a checkbox, some of the hidden form fields are supposed to be revealed using the jQuery function slideToggle(). The code itself is pretty simple and you can see an example her ...

Secure your messages with PHP encryption and decrypt them with JavaScript

I am looking for a way to encrypt a message using PHP and then decrypt it using JavaScript on the client side. I tried using Blowfish with mcrypt, but encountered an issue where PHP was outputting non-alphanumeric characters while JavaScript was only displ ...

Troubleshooting data binding problems when using an Array of Objects in MatTableDataSource within Angular

I am encountering an issue when trying to bind an array of objects data to a MatTableDataSource; the table displays empty results. I suspect there is a minor problem with data binding in my code snippet below. endPointsDataSource; endPointsLength; endP ...

Efficiently handling multiple JSON objects in a single PHP function

Currently, I am working on a project that involves populating two dropdown menus where the value of one depends on the other. Specifically, I have three dropdowns - one to select a class, and the other two for selecting subjects and exams based on the sele ...

The plugin "react" encountered a conflict while trying to sync with both the "package.json" and the "BaseConfig" files

Whenever I open Terminal in my react folder and try to start the react app using npm start, I always end up encountering an error on the browser. The error message states that the "react" plugin is conflicting between two paths: "package.json ยป eslint ...

Filter the output from a function that has the ability to produce a Promise returning a boolean value or a

I can't help but wonder if anyone has encountered this issue before. Prior to this, my EventHandler structure looked like: export interface EventHandler { name: string; canHandleEvent(event: EventEntity): boolean; handleEvent(event: EventEntity ...

Not all API results are being displayed by the Nextjs API function

I am facing an issue with rendering all the returns from the API in my Next.js application. The API, which is created in Strapi, is only displaying 1 out of the 3 possible returns. I am a beginner when it comes to using APIs and I suspect that the issue li ...

Adjusting the position of a stationary element when the page is unresponsive and scrolling

Managing a large web page with extensive JavaScript functionality can be challenging, especially when dealing with fixed position elements that update based on user scroll behavior. A common issue that arises is the noticeable jumping of these elements whe ...

How can I extract the value from the object returned by an AJAX call?

HTML file <div class="container"> <table id="headerTable" class="table table-bordered"> <thead> <tr> <th colspan="2">Header</th> </tr> </thead> <tbody> <c:forEach item ...

Which tools should I combine with Angular for developing both Android and iOS applications?

My primary focus has been on developing web apps using Angular, but now I am interested in creating native Android and iOS apps with Angular. I have heard about using Cordova, Capacitor, and NativeScript for this purpose, as alternatives to Ionic due to pe ...