admin管理员组文章数量:1384254
new to coding I'm trying to make a function that makes "abbreviations/acronyms" of words, e.g. 'I love you' -> 'ily'. I've tried rewriting the code in many ways but console.log only shows me the first letter of the first given word.
function makeAbbr(words) {
let abbrev = words[0];
let after = 0;
let i = 0;
for (const letter of words) {
if (letter === '') {
i = words.indexOf('', after);
abbrev += words[i + 1];
}
after++;
}
return abbrev;
}
const words = 'a bc def';
let result = makeAbbr(words);
console.log(result)
new to coding I'm trying to make a function that makes "abbreviations/acronyms" of words, e.g. 'I love you' -> 'ily'. I've tried rewriting the code in many ways but console.log only shows me the first letter of the first given word.
function makeAbbr(words) {
let abbrev = words[0];
let after = 0;
let i = 0;
for (const letter of words) {
if (letter === '') {
i = words.indexOf('', after);
abbrev += words[i + 1];
}
after++;
}
return abbrev;
}
const words = 'a bc def';
let result = makeAbbr(words);
console.log(result)
Share
Improve this question
edited May 18, 2022 at 14:15
Kuba Nowoszyński
asked May 18, 2022 at 14:13
Kuba NowoszyńskiKuba Nowoszyński
897 bronze badges
8
-
3
"I love you".match(/\b(\S)/g).join("")
– GottZ Commented May 18, 2022 at 14:15 - @GottZ Is there any simple way? Like changing something in my code? I'm not familiar with the "match" and "join" yet. – Kuba Nowoszyński Commented May 18, 2022 at 14:18
-
2
letter === ''
--->letter === ' '
andwords.indexOf('', after)
--->words.indexOf(' ', after)
- Note the space between single quotes. – Yousaf Commented May 18, 2022 at 14:19 -
basically
/\b(\S)/g/
is a regular expression that checks for word boundaries with\b
so something like the start and the end of a word.\S
checks for a non-whitespace character (excluding linebreaks). the(\S)
ensures you want to match what ever character is matched there./g
will match more than once..join
is simply a function that joins iterable objects like arrays and match results together, using what ever is specified as delimiter. – GottZ Commented May 18, 2022 at 14:21 -
1
words.indexOf(' ', after)
could also change towords.indexOf(letter, after)
, though this doesn't matter that much. It just reduces the amount of hardcoded values. – StackByMe Commented May 18, 2022 at 14:23
5 Answers
Reset to default 3here is my implementation of your function: Split the sentence into an array, get the first letter of each word and join them into one string.
const makeAbbr = string => string.split(' ').map(word => word[0]).join('');
console.log(makeAbbr('stack overflow'));
console.log(makeAbbr('i love you'));
`
Without using arrays. But you really should learn about them.
- Start by trimming leading and trailing whitespace.
- Add the first character to your acronym.
- Loop over the rest of the string and add the current character to the acronym if the previous character was a space (and the current character isn't).
function makeAbbr(words) {
words = words.trim();
const length = words.length;
let acronym = words[0];
for(let i = 1; i < length; i++) {
if(words[i - 1] === ' ' && words[i] !== ' ') {
acronym += words[i];
}
}
return acronym;
}
console.log(makeAbbr('I love you'));
console.log(makeAbbr('I love you'));
console.log(makeAbbr(' I love you '));
And here's the version for GottZ
function w(char) {
char = char.toLocaleLowerCase();
const coll = Intl.Collator('en');
const cmpA = coll.pare(char, 'a');
const cmpZ = coll.pare(char, 'z');
return cmpA >= 0 && cmpZ <= 0;
}
function makeAbbr(words) {
words = words.trim();
const length = words.length;
if(!length) return '';
let acronym = words[0];
for(let i = 1; i < length; i++) {
if(!w(words[i - 1]) && w(words[i])) {
acronym += words[i];
}
}
return acronym;
}
console.log(makeAbbr('I love you'));
console.log(makeAbbr('I love you'));
console.log(makeAbbr(' I love you '));
console.log(makeAbbr(' \tI ... ! love \n\r .you '));
console.log(makeAbbr(' \tI ... ! Löve \n\r .ÿou '));
Since you wanted something using your approach, try this (code is mented)
function makeAbbr(words) {
let abbrev = "";
for (let i = 0; i < words.length - 1; i++) { // Loop through every character except the last one
if (i == 0 && words[i] != " ") { // Add the first character
abbrev += words[i];
} else if (words[i] == " " && words[i + 1] != " ") { // If current character is space and next character isn't
abbrev += words[i + 1];
}
}
return abbrev.toLowerCase();
}
const words = 'a bc def';
let result = makeAbbr(words);
console.log(result)
If you want to use your approach exactly, you had a typo on the line specified. A character can never be ""
(an empty string), but a character can be a space " "
. Fixing this typo makes your solution work.
function makeAbbr(words) {
let abbrev = words[0];
let after = 0;
let i = 0;
for (const letter of words) {
if (letter === ' ') { // This line here
i = words.indexOf(' ', after);
abbrev += words[i + 1];
}
after++;
}
return abbrev.toLowerCase(); // Also added .toLowerCase()
}
const words = 'a bc def';
let result = makeAbbr(words);
console.log(result)
There are couple of things tripping you up.
let abbrev = words[0];
is just taking the first letter of the word string you passed into the function, and at some point adding something new to it.for (const letter of words) {...}
:for/of
statements are used for iterating over arrays, not strings.
Here's a remixed version of your code. It still uses for/of
but this time we're creating an array of words from the string and iterating over that instead.
function makeAbbr(str) {
// Initialise `abbrev`
let abbrev = '';
// `split` the string into an array of words
// using a space as the delimiter
const words = str.split(' ');
// Now we can use `for/of` to iterate
// over the array of words
for (const word of words) {
// Now concatenate the lowercase first
// letter of each word to `abbrev`
abbrev += word[0].toLowerCase();
}
return abbrev;
}
console.log(makeAbbr('I love you'));
console.log(makeAbbr('One Two Three Four Five'));
本文标签: How to make abbreviationsacronyms in JavaScriptStack Overflow
版权声明:本文标题:How to make abbreviationsacronyms in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744535833a2611309.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论