Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

98
Views
JavaScript for loop string to array

It just all of a suddenly crossed my mind we all know using regular for loop and push() method to convert string characters into an array

let myStr = "Perseverance";
let emptyArr = [];

for (let i = 0; i < myStr.length; i++) {
    emptyArr.push(myStr[i]);
}
console.log(emptyArr); 

then I decided to convert a whole string into a single element of an array just using push()...worked

let myStr = "Perseverance powers";
let emptyArr = [];

for (let i = 0; i < myStr.split().length; i++) {
  emptyArr.push(myStr);
}
console.log(emptyArr);

Now here when I want to separate each word into a single element of an array just using push() I can't... Here is my question: How can I convert each word of the string into a single element of an array using only push() and for loop

P.S. A lot ways exist yet it was just a thought came to my mind 'what if' Thanks

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

You can use JavaScript's split to create an array of words.

const myStr = "Perseverance powers";
const arr = myStr.split(' ');
console.log(arr);

documentation for split

Here's what I came up with if you want to do this using push

const str = 'Perseverance powers';
const arr = [];
let temp = '';

str.split('').forEach(character => {
    if(character === ' ') {
    arr.push(temp);
    temp = '';
  } else {
    temp += character;
  }
})
arr.push(temp);

console.log(arr)

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!