user11010005
user11010005

Reputation:

Issue with finding empty space to create acronym: nested for loops

I need to find an empty space to create an acronym, having issues with the first letter, the rest much easier..

let word = "";
let p = "Tim Hortans Returant"


for (let i=0 ; i<p.length; i++){
    
    if (p.charAt(i) != " "){
        word+= i ; 
        }
        if(p.charAt(i) === " "){
            word+= p.charAt(i+1) 
            console.log(word)
    }
}

Upvotes: 0

Views: 39

Answers (1)

CertainPerformance
CertainPerformance

Reputation: 370789

Split by spaces, map each word to its first character, then join:

const p = "Tim Hortans Returant"
const word = p
  .split(' ')
  .map(word => word[0])
  .join('');
console.log(word);

Or, perhaps more efficiently, with a regular expression, capture the first character of each word, match the rest of the word, and replace with the captured character:

const p = "Tim Hortans Returant"
const word = p
  .replace(/(\S)\S* */g, '$1');
console.log(word);

If you had to use a for loop (not recommended, it'll require verbose and messy code), add the i + 1th character to word when a space is found:

const p = "Tim Hortans Returant";
let word = p[0];

for (let i = 0; i < p.length; i++) {
  if (p[i] === ' ') {
    word += p[i + 1];
  }
}
console.log(word);

Upvotes: 1

Related Questions