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

224
Visualizações
Substitute all letters except the first in each word
text = "Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,";

substitute_with = "_";

const regex = '\B[A-Za-z]';
// const regex = '\B\w';
// const regex = '(\w{1})\w*';

var result = text.replaceAll(regex, substitute_with);

I would like to substitute with underscore all letters except the first in each word.

What can I try next?

about 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Use the g (global) flag with replace():

const text = "Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,";
const substitute_with = "_";

const regex = /\B[A-Za-z]/g;
var result = text.replace(regex, substitute_with);

console.log(result);

L____ I____ h__ b___ t__ i_______'s s_______ d____ t___ e___ s____ t__ 1500_,


Of course, this can also be done without regex using split(), substring(), repeat() and join():

const result = text.split(' ')
    .map(w => w.substring(0, 1) + substitute_with.repeat(w.length - 1))
    .join(' ');
about 4 years ago · Santiago Trujillo Relatório

0

You could match all words first, then separate the head and tail of the word and replace all the letters in the tail porition.

const text = "Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,";

const result = text.replace(
  /\b\S+\b/gi,                               // For each word
  (g0) => g0.replace(                        
    /\b([a-z])(.+)\b/i,                      // Grab the head and tail
    (_g0, _g1, _g2) =>
      `${_g1}${_g2.replace(/[a-z]/gi, '_')}` // Keep head, replace all others with '_'
  )
);

console.log(text);
console.log(result);
.as-console-wrapper { top: 0; max-height: 100% !important; }

about 4 years ago · Santiago Trujillo 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