1

I need to add the string Sr. at the beginning of a string if it is missing at all or has missing space or dot.

These strings...

Sr. Name
Sr.Name
Name
Sr Name
Sr name
Sr. name
sr.name

...should always result in the string Sr. Name.

I tried to split the string: string.split['.'], but this would not take all cases as shown above. So I tried some regex: string.replace(/Sr. /, 'Sr. ').

user3142695
  • 15,844
  • 47
  • 176
  • 332

2 Answers2

2

From the beginning of the string, optionally match sr (case insensitive), followed by an optional . and a space, and replace with 'Sr. ' (trailing space included):

`Sr. Name
Sr.Name
Name
Sr Name
Sr name
Sr. name
sr.name`
  .split('\n')
  .forEach((str) => {
    console.log(
      str.replace(/^(?:sr\.? ?)?/i, 'Sr. ')
    );
  });
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
0

If your data is in string format like below than you can use regex with multiline flag. Instead of split by \n and than do some manipulation and than join back by \n

/^(?:sr\.?\s*)?/igm

let op = `Sr. Name
Sr.Name
Name
Sr Name
Sr name
Sr. name
sr.name`.replace(/^(?:sr\.?\s*)?/igm,'Sr. ')

console.log(op)
Code Maniac
  • 37,143
  • 5
  • 39
  • 60