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

320
Views
¿Cómo escribo una función en JS para devolver la abreviatura de las palabras?

Por ejemplo:

 makeAbbr('central processing unit') === 'CPU'

No pude encontrar mi error. Aprecio tu ayuda.

 function makeAbbr(words) { let abbreviation = words[0]; for (let i = 1; i < words.length; i++) { if (words[i] === '') { abbreviation += words[i + 1]; } } return abbreviation.toUpperCase(); } console.log(makeAbbr('central processing unit'));

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

0

Solo necesita cambiar las words[i] === '' en words[i] === ' ' . '' es una cadena vacía.

Otra opción es dividir la cadena pasada.

 function makeAbbr(str) { // words is [ "central", "processing", "unit" ] let words = str.split(/\s+/); let abbreviation = ''; for (let i = 0; i < words.length; i++) { abbreviation += words[i][0]; } return abbreviation.toUpperCase(); }
about 4 years ago · Juan Pablo Isaza Report

0

Esto generalmente funcionará en la abreviatura de palabras que usan el primer carácter de cada palabra separado por un espacio.

 function makeAbbr(words) { // result abbreviation let abbreviation = ''; // store each word into an array using split by space let wordArray = words.split(' '); // iterate through the word array for (let i = 0; i < wordArray.length; i++) { // take the first character in each word into the result abbreviation abbreviation += wordArray[i][0]; } // return the abbreviation with all of them being upper case return abbreviation.toUpperCase(); } // test case console.log(makeAbbr('central processing unit'));

about 4 years ago · Juan Pablo Isaza Report

0

Una solución de una línea:

 function makeAbbr(words) { return words.split(' ').map(word => word[0].toUpperCase()).join(""); } console.log(makeAbbr('central processing unit'));

Estamos convirtiendo la oración de string en una matriz de palabras separadas por un espacio ( .split(" ") ), luego mapeando o transformando cada palabra en la matriz a su primera letra, así como capitalizándola: .map(word => word[0].toUpperCase()) , luego une los elementos de la matriz en una cadena con "nada" "" como separador:

"central processing unit" -> ["central", "processing", "unit"] -> ["C", "P", "U"] -> "CPU"

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!