Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

147
Visualizações
How to split words without spaces into a sentence which each word start with capital letter using Javascript

Given a string like this "HowToMakeALiving", I want to split it and make it as "How to make a living". Another situation is "howToMakeALiving", so the first word "how" does not start with capital letter while other words start with capital and I still want to split it and generate "How to make a living"

There are some questions in the community, but they are rarely JS related or need to use packages, and their situation is more complicated, the given string is all lowercase.

So the question is how can I do that by regex in Javascript or any other better method?

about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You could use a regular expression:

function splitWords(s) {
  return s.match(/.[^A-Z]*/g).map((word, i) =>
    (i ? word[0].toLowerCase() : word[0].toUpperCase()) + word.slice(1)
  ).join(" ");
}

let words = splitWords("howToMakeALiving");
console.log(words);
words = splitWords("WhyIHadMyDNATakenInParis");
console.log(words);

The regular expression looks for any character (.) followed by a series of non-capital characters. Each find is a word.

The loop distinguishes between the first word (i == 0) and other words (i is truthy). The first character of each word is cast to upper case (first word) or lower case (all other words).

Finally, the words are joined together into a phrase by joining them with a space as separator.

Alternative for capitalised abbreviations

If it is needed to capture abbreviations like "DNA" and the personal pronoun "I", you could:

  • Make an explicit comparison with "I", such that it is always put as a capital.
  • Only break a word when there is at most one more capital following the break -- you can use a regular expression with look-ahead features.

function splitWords(s) {
  return s.match(/.([^A-Z]+|.*?(?=[A-Z]([^A-Z]|$)|$))/g).map((word, i) =>
    (i && word !== "I" && (word.length < 2 || word[1] != word[1].toUpperCase()) 
        ? word[0].toLowerCase() 
        : word[0].toUpperCase()
    ) + word.slice(1)
  ).join(" ");
}

let words = splitWords("howToMakeALiving");
console.log(words);
words = splitWords("WhyIHadMyDNATakenInParis");
console.log(words);
words = splitWords("iHateHavingADNATestTaken");
console.log(words);

about 4 years ago · Juan Pablo Isaza Relatório

0

Option 1: You would do this with .match() build method like this:

let textvalue = 'howToMakeALiving'
let splitdata = textvalue.match(/[A-Z][a-z]+|[0-9]+/g).join(" ")
console.log(splitdata)

Option 2: You can use string.split() method also supports regex it can be achieved like this

let textvalue = 'howToMakeALiving'
let splitdata = textvalue.split(/(?=[A-Z])/);
console.log(splitdata)

about 4 years ago · Juan Pablo Isaza Relatório

0

Try this, it may have a bug or two but it will send you on the right path.

var res = '';
var chars = 'HowToMakeALiving'.split();
var lastChar = '';
for (var i = 0; i < chars.length; i++) {
  if (lastChar = '')
    lastChar = chars[i];
  if (chars[i].toUpperCase() != chars[i] && lastChar.toUpperCase() != lastChar)
    res = res + ' ';
  res = res + chars[i];
}

console.log(res)

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda