简体   繁体   中英

Match and replace depending on the regex pattern in javascript

I have not been able to deploy a working process to use multiple regex patterns to match and replace the following patterns of names. I need to extract the last name, first name, middle initial or fill it with white space, and place commas between them Examples:

In:

  • "HILL,ADAM APRN"
  • "SMITH,JOHN B APRN"
  • "JONES-WILSON,ROBERT APRN"

Out:

  • "HILL,ADAM, ,APRN"
  • "SMITH,JOHN,B,APRN"
  • "JONES-WILSON,ROBERT, ,APRN"

The procedure I used stopped on the first name

Any assistance would greatly be appreciated.

Thank you - Matt

If you really need to use a regular expression, (\\w+(?:-\\w+)?),(\\w+)\\s(?:([a-zA-Z]{1})\\s)?(\\w+) will give you the captures that you need.

However, it would be much easier to use the split function like...

var name = "HILL,ADAM APRN";
var newName = name.split(/[ ,]/).join(',')
var str = "HILL,ADAM APRN";
var blocks = str.match(/ /g).length;
var nuStr = (blocks==1 ? (str.replace(/ /, ', ,')) : (str.replace(/ /g, ',')));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM