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

195
Visualizações
regex excluding a char before a symbol in JS

I currently want to make the first letter of a city name uppercase; but since in my country we have a lot of cities with a multiple words composed name (eg. New York), i am currently using this regex:

/\w\S*/g

so I am using this function

function capitalizeWords(myString) {
  return myString.replace(/\w\S*/g, w => w.replace(/^\w/, c => c.toUpperCase()))
}

so I can change new yorkin New York.

But now I have a small issue, I have some cities like

sauze d'oulx

and I need to convert it to Sauze d'Oulx, excluding the d, or in any case the first character before the ' symbol.

What is the trick to exclude one char before a known one?

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

0

You can define all your exceptions as alternatives before matching and capturing your expected match:

const texts = ["new york", "sauze d'oulx"];
const capitalizeWords = (myString) =>
  myString.replace(/\bd['’]|(\w)(\S*)/g, (m, g, h) => g ? g.toUpperCase() + h : m);
  
for (const text of texts) {
  console.log(text, '->', capitalizeWords(text));
}

The \bd['’]|(\w)(\S*) regex matches

  • \bd['’] - a d' or d’ after a non-word char or at the start of string
  • | - or
  • (\w)(\S*) - a word char captured into Group 1 (g in the code above) and then zero or more non-whitespaces into Group 2 (h in the code above).

The (m, g, h) => g ? g.toUpperCase() + h : m replacement means that the replacement is the match itself if Group 1 did not match, else, the char matched with \w is capitalized.

Extending with di preposition:

const texts = ["new york", "sauze d'oulx", "bagno di romagna"];
const capitalizeWords = (myString) =>
  myString.replace(/\bd(?:['’]|i\b)|(\w)(\S*)/g, (m, g, h) => g ? g.toUpperCase() + h : m);
  
for (const text of texts) {
  console.log(text, '->', capitalizeWords(text));
}

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