I need help with string manipulation in JavaScript. I have a sentence like this:
let sentence = "Good morning beautiful world";
I want to transform it so it becomes:
"GOO_MOR_BEA_WOR"
Basically I want to grab the first three letters from every word, make them uppercase, and put an underscore between each group. I already know how to make letters uppercase with .toUpperCase() but I’m stuck on the rest of the logic. How can I split the words, take only the first 3 characters from each, and then join them back with underscores?
Just chain the string methods together. Split the sentence into words, map over each word to grab the first 3 characters and uppercase them, then join with underscores.
let sentence = "Good morning beautiful world";
let result = sentence.split(' ').map(word => word.substring(0, 3).toUpperCase()).join('_');
console.log(result); // "GOO_MOR_BEA_WOR"
Substring’s great here - it won’t break if a word’s shorter than 3 characters, just returns the whole word. I use this pattern all the time for making short IDs from longer text.
Watch out for edge cases depending on what you’re doing. If your string has extra spaces or empty strings, filter them out first with sentence.split(' ').filter(word => word.length > 0) before mapping. I hit this when processing user input with messy spacing. Also think about punctuation - ‘hello, world!’ will grab the comma and exclamation in your 3-character slice. For clean results, strip non-alphabetic characters first with a regex replace.
u could even use slice instead of substring if u like. both do the same thing with positive indexes, but slice feels cleaner to me. the split > map > join way is def the best approach tho - solid solution!
This topic was automatically closed 6 hours after the last reply. New replies are no longer allowed.