How can you transform a string into an array in Javascript with only one parameter and no reliance on built-in methods like split()?

How can a String be converted to an Array in Javascript without utilizing the split() function or any other pre-built methods?

Here is an example:

str = "Iam a fullstack javascript developer"

The resulting array should look like this:

arr = [ 'Iam', 'a', 'fullstack', 'javascript', 'developer' ]

To verify, you can run this code:

console.log(arr[0]) // Iam

Answer №1

let message="I am a backend Python developer";
let messageChars;
[...messageChars]=message;
let charArray=messageChars.reduce((accumulator, currentValue)=>{if(currentValue==" ") accumulator.push(""); else accumulator[accumulator.length-1]+=currentValue; return accumulator;},[""]);
console.log(charArray);

[...messageChars]=message converts the string into an array of characters.
The reduce method initializes with an array containing an empty string ([""]),
and adds characters or inserts a new element if there is a space.

Answer №2

Check out the following code for a clever solution

function convertStringToArray(sentence) {
    let wordArray = [''];
    let index = 0;

    for (let charIndex = 0; charIndex < sentence.length; charIndex++) {
        if (sentence.charAt(charIndex) == " ") {
            index++;
            wordArray.push('');
        } else {
            wordArray[index] += sentence.charAt(charIndex);
        }
    }
    return wordArray;
}

const result = convertStringToArray("I love programming in Python")
console.log(result[1]) // love

Answer №3

A method that recursively uses the indexOf and slice functions

str = "Iam a fullstack javascript developer";

const splitWords = (str, arr) => {
  const index = str.indexOf(" ");
  if (index > -1) {
    arr.push(str.slice(0, index));
    splitWords(str.slice(index + 1), arr);
  } else {
    arr.push(str);
  }
  return "";
};

const divideIntoChunks = (str) => {
  const arr = [];
  splitWords(str, arr);
  return arr;
};

console.log(divideIntoChunks(str));

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

Presenting a ui-router modal while maintaining the parent state's refresh-free appearance

I have implemented a unique feature in my angular app called modalStateProvider. It allows me to easily have modals with their own URLs. // Implementing the modalStateProvider app.provider('modalState', [ '$stateProvider', function ...

Is the create attachment function of the Microsoft Graph API not functioning properly?

I've been trying to create an attachment for my messages by following the documentation provided, but unfortunately, the API seems to be giving me some trouble. I referred to the document at for guidance. Below is the JavaScript code that I have bee ...

What is the function of `function(data){}` in the context of JQuery's $.get

Within my MySQL database, there exists a column for VideoID and VideoCode In backend.php, I have crafted a PHP function with the goal of selecting the subsequent video from the list in the following manner: $VideoID = 0; function nextvideo(){ global ...

Button for Autocomplete Component in React Material UI to be displayed after clearing the field

After successfully adding a search button to my Autocomplete Component on Material UI, I encountered an issue where the button always appears before the clear button as shown in this image: https://i.sstatic.net/Tx5zv.png I am seeking assistance on how t ...

Having trouble locating the web element within a div popup while utilizing Node.js and WebdriverIO

I need assistance with a seemingly simple task. I am currently learning webdriverjs and attempted to write a short code to register for an account on the FitBit website at URL: www.fitbit.com/signup. After entering my email and password, a popup appears as ...

Three.js is experiencing difficulties in loading textures for custom Geometry with ShaderMaterial

A Geometry (pyramid) is defined here with four vertices and 4 faces - var geom = new THREE.Geometry(); geom.vertices.push(new THREE.Vector3(0,100,0), new THREE.Vector3(-100,-100,100), new THREE.Vector3(0,-100,-100), new THREE.Vector3(100,-100,100)); geom ...

A guide on retrieving various elements from a 3D numpy array employing an array of 3D indices

I have a situation where I am working with two arrays - array A and array B. Array A is a 3D array with dimensions (360,360,360) while array B has the shape (259200,3). Each row in array B represents an index of array A. Is there a more efficient way to c ...

Retrieving elements from Select2 once the data has finished loading

Looking for a way to trigger the open method and select an item with select2? Here's what I have tried: $(".select").select2('open') $(".select").on('select2-loaded', function (e) { items = e.items.results; ...

How can I iterate through XML nodes using JavaScript?

I attempted to iterate through list items from an XML file using JavaScript. However, the list data is not displaying with bullet points. Below is my code: Data.xml <?xml version="1.0"?> <paintings> <cd> <para>posuere lacus in, ...

What is the best way to associate an array of objects with another array in React or JavaScript?

const arrayObj = [{ id: 123, country: "IND" value: "" }, { id: 153, country: "AUS" value: "" }, { id: 183, country: "FRA" ...

Set the cursor in the textbox automatically when the page first loads

Is there a way to set focus on a text box when a page loads? I've attempted using the autofocus attribute but it hasn't worked for me. You can view my form here: http://pastebin.com/xMJfQkcs ...

Show a pop-up window when a button is clicked, just before the page redirects

Is there a way to display a popup message before redirecting to another page when clicking on a button? Here's the scenario: <a href="addorder.php?id=<? echo $row01['id']; ?>" ><button id="myButton" class="btn btn-primary btn ...

"Querying MySQL databases with PHP arrays using the SELECT, FROM, and

I am attempting to create a system where the array data is transformed to match the ID of its corresponding entry in another MySQL table based on checkboxes selected in a PHP script. Here is the code snippet: $insertSQL2 = "INSERT INTO test (Testing) VAL ...

What is the best way to update properties of an array object using a map in pure JavaScript for maximum efficiency?

Looking for an efficient solution to replace property keys in an array of objects using a map? Here's an example scenario: // Consider an array of objects: var records = [ {"Id": "0035w000036m j7oAAA", "Business Phone": ...

Chapter on how to generate a new bootstrap row for every pair of elements in Angular

I am facing a challenge with adding a row after every 2 elements in an ngFor loop. I have an array called studentNames which looks like this: studentNames=[ { name:"Jonas", age:22, number:"1234" }, { name:"Mathil ...

The plugin's element is not compatible with jQuery methods

This particular plugin is designed to enhance the appearance of checkbox inputs. It creates a more visually appealing version of standard checkboxes. However, I have encountered an issue with one of the variables in the code. Let's discuss the theLab ...

What is the best way to send JSON data to a code behind method instead of a Webmethod?

I have a dilemma with handling JSON data in my code behind to bind it to an obout grid. While I am aware of passing data using the <WebMethod>, I've encountered limitations as the method is static, making it difficult to bind the data to any gri ...

Activate the div when hovering over the span

Experiencing an issue with triggering a visible div while hovering over a span. Here is the code structure: <ul class="products"> <li> <a href="somelink"> <img src="some image"> <div class="overlay"> Some Text</div> & ...

Attempted to execute my testing script with mocha, however encountered a "Reference Error: beforeEach is not defined" issue

While running my test script for a todo app in node.js using Mocha, I encountered a reference error stating that "beforeEach is not defined". The code snippet causing the issue is shown below: const {app} = require('./../server'); const {Todo} ...

Show the components only if the final digit in their identification number is less than i

I have several span elements with IDs like "tag1", "tag2", etc. I want to display only the spans whose ID ends with a number less than 19. These elements are part of a class called "notVis", which is hidden by default using $(".notVis").hide(); when the ...