-1

My original string = A abc, B xyz, C mlk ooo

How can I remove single letter of each element: A B C?

Expected Output = abc, xyz, mlk ooo

Azhar Khan
  • 3,829
  • 11
  • 26
  • 32
SHDT
  • 21
  • 3
  • standalone letters commonly appear in human readable text, i.e., "a", "i". Are you sure that, for example, stripping out the text before the first space is not a better approach? – Ronnie Royston Oct 22 '22 at 05:23

1 Answers1

2

You could use a regex to replace a single letter (indicated by a letter with a word-break \b on either side of it) followed by some number of spaces with nothing:

const str = "A abc, B xyz, C mlk ooo"

const output = str.replace(/\b[a-z]\b\s*/ig, '', str)

console.log(output)

Regex demo on regex101

Nick
  • 138,499
  • 22
  • 57
  • 95
  • Nice anwser,but I haven't see any `()` in your regex expression,could you explain a bit,please? – flyingfox Oct 22 '22 at 04:47
  • @lucumt why do you think there should be any `()`? – Nick Oct 22 '22 at 05:12
  • ,I am not very good at regex,I just think need to get the result by group – flyingfox Oct 22 '22 at 05:13
  • @lucumt not in this case, I am replacing the entire match (a letter followed by 0 or more spaces) with nothing. So I don't need any groups. – Nick Oct 22 '22 at 05:14
  • @Nick Thank you. I use some special font and this ouput wrong. Please see screenshot: https://ibb.co/8PyyK02. How can fix for my font. Eg string = "T Trâm, S - Sơn, T Tiên". Thank you – SHDT Oct 22 '22 at 09:57
  • @SHDT you should be able to use `str.replace(/\b\p{L}\b\s*/igu, '', str)` – Nick Oct 22 '22 at 10:01
  • @Nick thank you. Input string = "= "T Trâm, S - Sơn, T Tiên". But this output is wrong: "Tr, - , Ti" . Please see: https://ibb.co/Srvtv4j . Correct output should be = "Trâm, Sơn, Tiên" . – SHDT Oct 22 '22 at 10:32
  • @SHDT sorry, forgot that `\b` doesn't work with unicode letters. `/(?<!\p{L})\p{L}(?!\p{L})\s*/igu` should work – Nick Oct 22 '22 at 10:38
  • @SHDT no worries - I'm glad that worked for you – Nick Oct 22 '22 at 11:03