Reputation:
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
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 + 1
th 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