Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

302
Views
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 answers
Answer question

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 Report

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 Report

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!