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

303
Visualizações
Is there a regex to remove everything after comma in a string except first letter

I am trying to remove all the characters from the string after comma except the first letter. The string is basically the last name,first name.

For example:

Smith,John

I tried as below but it removes comma and everything after comma.

let str = "Smith,John";
str = str.replace(/\s/g, ""); // to remove all whitespace if there is any at the beginning, in the middle and at the end
str = str.split(',')[0];

Expected output: Smith,J

Thank you!

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

0

Or try (,\w).* with replace:

let str = "Smith,John";
str = str.replace(/(,\w).*/, '$1');
console.log(str);

about 4 years ago · Juan Pablo Isaza Relatório

0

Try this regex out:

\w+,\w

This matches one or more characters before the comma and then matches only 1 character.

Here is the demo: https://regex101.com/r/bKpWt7/1

Note: \w matches any character from [a-zA-Z0-9_].

about 4 years ago · Juan Pablo Isaza Relatório

0

Taking optional spaces around the comma in to account, and perhaps multiple "names" before the comma:

 *([^\s,][^,\n]*?) *, *([^\s,]).*
  • * Match optional spaces
  • ( Capture group 1
    • *([^\s,] Match optional spaces and match at least a single char other than a whitespace char or a ,
    • [^,\n]*? Match any char except a , or a newline non greedy
  • ) Close group 1
  • *, * Match a comma between optional spaces
  • ([^\s,]) Capture group 2, match a single char other than , or a whitespace char
  • .* Match the rest of the line

Regex demo

In the replacement using group 1 and group 2 with a comma in between $1,$2

const regex = / *([^\s,][^,\n]*?) *, *([^\s,]).*/;
[
  "Smith,John Jack",
  "Smith Lastname , Jack John",
  "Smith  , John",
  " ,Jack"
].forEach(s => console.log(s.replace(regex, "$1,$2")));

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