Is it possible to divide a text string into distinct arrays using spaces?

One method I am familiar with for splitting a string involves using the .split() method, like so:

function split(txt) {
    return txt.split(' ');
}

When executed, this function would return ['hello', 'world'] if provided with the value "hello world".

However, my goal is to split the string in the same manner (by spaces), but instead of combining them into a single array, I aim to separate each word into its own array without having prior knowledge of the string's length or the number of spaces present.

For instance, the desired output would be [['hello'], ['world']]

Answer №1

To transform the outcome into an array, one could use mapping.

function separate(input) {
    return input.split(' ').map(str => [str]);
}

console.log(separate('hello world'));

Answer №2

function breakApart(input) {
  return input.split(' ').map(function(word) {
    return [word];
  });
}

console.log(breakApart('hello world'));

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

Using JSF 2.1 for Ajax autocomplete with server search triggered only when user pauses typing

Currently, I am working on developing an autocomplete feature that involves database search based on user input events (specifically onkeyup) in a <h:inputText />. There are two specific preconditions that need to be met for the application to perfo ...

Could this be a Vue.js memory leakage issue?

Check out this component's code: import { defineComponent, ref } from "@vue/composition-api"; const template = /* html */ ` <div> <nav> <button @click="showCanvas = !showCanvas">Toggle</button> </nav>a <can ...

Having difficulty with setting up the Webpack css-loader, encountering an error during compilation

As a newcomer to webpack, I have been experimenting with creating my own build by modifying an existing one. One issue I encountered was the css not compiling, so I took the following steps: Confirmed that there were no css loaders already included in th ...

Utilizing a CSV file as a Map with D3 and JavaScript

After thorough research through JavaScript and D3 documentation, I have not been able to find a solution to my problem... Is it feasible to import a CSV file with the following format: header, header string1, string string2, string ... stringN, string an ...

Tips for successfully sending an array via an XMLHttp Get request

I am currently working on a project where I need to utilize all the values from an array in my GET request. The code snippet below outlines my approach: function executeRequest(){ let data = ['value1', 'value2', 'value3'] ...

What could be the reason behind PHP not picking up my AJAX request string?

I'm encountering an issue where PHP is not recognizing my request string as defined. When I include $_GET['ask'] in my PHP file, it triggers the error message - Notice: Undefined index: ask. Interestingly, when I manually input the query in ...

Can you determine if a function is a generator function if .bind() has already been applied to it?

It seems like using .bind(this) on a generator function is interfering with determining if the function is actually a generator. Any suggestions on how to resolve this issue? function checkIfGenerator(fn) { if(!fn) { return false; } ...

"Transforming JSON data into a format compatible with Highcharts in PHP: A step-by-step

Currently facing an issue with converting the given array format into a Highcharts compatible JSON to create a line chart. Although everything else is functioning correctly, I am struggling with this specific conversion task. { name: [ 1000, ...

"Utilize AJAX to submit the value of the text box input from a jQuery slider when the Submit Button

Whenever I adjust the sliders, the value is shown in an input textbox. However, when I move the slider and check the values echoed from the textboxes on another PHP page, they are always displaying as 0. Even after clicking the submit button, it still echo ...

Sorting items in backbone.js can be achieved by using the sortBy method

Currently, I am delving into learning backbone.js and have decided to create my own Todo application using backbone.js along with a local storage plugin. At this point, I have successfully developed the Todo app where you can add and remove tasks. However, ...

After clicking multiple times within the modal, the modal popup begins to shift towards the left side

I successfully implemented a modal popup in my project, but encountered an issue where the popup moves to the left side if clicked multiple times. Despite searching extensively online, I have not been able to find a solution to this problem. Below is the ...

What are alternative ways to communicate with the backend in Backbone without relying on model.save()?

Is there a more effective method to communicate with my backend (node.js/express.js) from backbone without relying on the .save() method associated with the model? Essentially, I am looking to validate a user's input on the server side and only procee ...

Trouble with using $.ajax to call a PHP function

Hey everyone, I hate to ask for help but I'm really stuck on this issue. I've tried everything and followed all the scenarios on this site, but I just can't seem to get it working. I even added alerts and echoes, but the function doesn' ...

Is there a way to asynchronously load image src URLs in Vue.js?

Why is the image URL printing in console but not rendering to src attribute? Is there a way to achieve this using async and await in Vue.js? <div v-for="(data, key) in imgURL" :key="key"> <img :src= "fetchImage(data)" /> </div> The i ...

Issue with Bootstrap error class not functioning in conjunction with hide class

I need to create a form that slides down two input fields when an error occurs, and I want them to have the bootstrap error class. The 'error' class works fine without the 'hide' class being present, but when the 'hide' class ...

Verify the operation within a pop-up box using ruby watir

Is it possible to confirm a modal dialog window in Internet Explorer using Ruby Watir? Here is the JavaScript code for the modal dialog: jQuery('#yt100').on('click', function(){return confirm('modal dialog window text');}); ...

Angular 7: Finding the variance between array elements

How can I subtract the values from the first 3 rows of the table? The formula is TVA Collectée - TVA Déductible - TVA Déductible/immo If the result is positive, it should be displayed in the box labeled TVA à Payer. If it's negative, it should g ...

Using express.js to send multiple post requests to the same url

My website features a login form where users input their information. Upon submission, a post request is made to check the validity of the provided information. If successful, users are redirected back to the login form where they must enter the code sent ...

Trigger a JavaScript function after Angular has completed its process

Once all data binding is completed and there are no more tasks for the Angular javascript to perform, I need to execute a function that toggles the display of certain divs. Attempted Solutions I want to avoid using timeouts: The timing of Angular's ...

Incorporate Bookmarklet into GitHub README.md

Trying to add a Bookmarklet to a Github README.md, but encountering issues with the markdown code: [Bookmarklet](javascript:alert('not-working')) It appears that the javascript in the link is being stripped out from the compiled output. Is this ...