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

Select items from object based on a specified array of IDs

I am facing a challenge with my list of objects that each have an array associated with them. For instance, take a look at this example: "-KpvPH2_SDssxZ573OvM" : { "date" : "2017-07-25T20:21:13.572Z", "description" : "Test", "id" : [ { ...

Transferring information to a controller using ajax in ASP.NET Core

I am encountering an issue with sending data to the controller through ajax. The value goes as "null". Can someone please assist me with this? Here are my HTML codes: <div class="modal fade" id="sagTikMenuKategoriGuncelleModal" data ...

Is utilizing unregistered HTML elements for semantic purposes considered poor practice?

When it comes to styling and semantic purposes, I am considering using unregistered web components. This means utilizing tags like <t-card></t-card> without registering them with customElements.define. Surprisingly, the browser and stylesheets ...

Determining whether an element possesses an attribute labeled "name" that commences with a specific term, apart from the attribute "value"

I'm planning to use distinctive data attributes with a prefix like "data-mo-". Let's say I have the following elements: <span data-mo-top-fade-duration="600">Title 1</span> <span data-mo-bottom-fade-duration="600">Title 2</ ...

Is there a way to execute a Node 6 npm package within a Node 5.6.0 environment?

I am currently utilizing a tool called easy-sauce to conduct cross-browser JavaScript tests. Essentially, my package.json file references this tool for the test command: { "scripts": { "test": "easy-sauce" } } Everything runs smoothly when I exec ...

What is the best way to retrieve AJAX responses from JSON data that contains multiple sets of information

["12-Feb-2017","06-Feb-2017","5","45","40","Neha shishodia","USD","unit2","phase1","Change Request","Client Approval Awaited"]["07-Feb-2017","04-Feb-2017","6","54","48","Neha shishodia","USD","unit2","phase1","Change Request","Manager Approval Awaited"] T ...

Enable the button if at least one checkbox has been selected

I've written some code similar to this: $('input[type=checkbox]').click(function(event) { $('.chuis').each(function() { if(this.checked) { $('#delete_all_vm').prop("disabled",false); } ...

Tips for delivering a variable to a React Native Stylesheet

Is there a way to pass a variable to the "shadowColor" property in my stylesheet from an array declared in the code above? I keep encountering a "Can't find name" error. Attempting to use a template literal has not resolved the issue. Any assistance w ...

.parseXML yields no results

I am struggling to interpret a response from a server that should be in XML format. While I am new to web development, I am trying to quickly grasp JavaScript for an assignment. Unfortunately, I cannot control the server. My code snippet is as follows: . ...

Stop RequireJS from Storing Required Scripts in Cache

It seems that RequireJS has an internal caching mechanism for required JavaScript files. Whenever a change is made to one of the required files, renaming the file is necessary in order for the changes to take effect. The typical method of adding a version ...

The robots.txt file in Nuxt.js allows for multiple disallow directives for each user agent

With the Nuxt module called nuxt-robots, how can I set up multiple disallow rules per user agent? Currently, my configuration looks like this: robots: () => { return { UserAgent: '*', Disallow: '/search/', Si ...

Obtain the attribute value from an HTML option element

Here is the code snippet I am working with: <select class="form-control valid"> <option isday="False" value="2">Value 1</option> <option isday="True" value="3">Value 2</option> <option isday="True" value="4"> ...

Learn the process of updating an Xero invoice seamlessly with the xero-Node integration

After successfully integrating Xero with my app for accounting and billing purposes, I am now looking to update a previous invoice that was created in the past on Xero. Is there a solution available for this? Any suggestions would be greatly appreciated. ...

Organize Dates in React Table

I need help with sorting the Date column in my code. Currently, the sorting is being done alphabetically. Here is the JSON data and code snippet: JSON [ { "date": "Jun-2022" }, { "date": "Jul-2022" } ...

Implement a menu that can be scrolled through, but disable the ability to scroll on the body of the website

When viewed on a small screen, my website transforms its menu into a hamburger button. Clicking the button toggles a sidebar displaying a stacked version of the menu on top of the normal website (position: fixed; z-index: 5;). This sidebar also triggers a ...

PHP MySQL Table with a Date Range Filter

As someone who is new to PHP, I have a question. How can I set up a date range filter? I've looked at tutorials, but they haven't worked for me. I do have some code, but it doesn't include any functions. I want to implement this in a CRUD t ...

"Utilizing the power of mapping in React to dynamically generate and return an

Hello everyone! I'm currently working on a project where I am making a get request to a Google API and fetching some data. Initially, the state value is empty, but after receiving the ajax response, I expect the state values to be updated using setSta ...

Retrieving Hyperlinks from JavaScript Object for Integration with D3-Created Table

Issue: I'm facing a problem where the HTML link extracted from an Associative Array is treated as a string instead of being applied as a clickable link in the browser. For a detailed visual example and code snippet, visit: http://example.com/code Da ...

The validation did not pass using the validate.min.js script

Hey everyone, I had this code working perfectly before but now it seems to have stopped working. Can anyone help me figure out what's going on? Below is the form I am referring to: <form action="CreateUser" method="POST" id="subscribe"> & ...

How to use AJAX to retrieve data from a JSON file hosted on an external URL?

Is it possible to extract data from a JSON file that belongs to an external source such as ABS, a company that provides weather information? The weather data is stored in a JSON File. Why am I unable to access this information and save it? & ...