Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

305
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda