What you're doing and why this doesn't work out correctly:
In your scenario,
displayName = 'Fernando, John Maurice'.
The first thing you do is split this using regular expression
This splits the string on each occurence of a
, or (
|) a space
The result of this split is an array with 4 elements:
['Fernando', '', 'John', 'Maurice'] (as you can see, all spaces and comma's are no longer present). When you
reverse() this, the resulting array is
['Maurice', 'John', '', 'Fernando']. And
join()ing these elements to a new string with spaces results in
'Maurice John Fernando'
So the solution would be to not split the initial string on spaces, but only on the comma. The regex will be just this:
/,/. Now the array will be just two elements after the
['Fernando', ' John Maurice'] (notice the space before John is still here because we just split on the
, and not the space). Reversing this array will result in array
[' John Maurice', 'Fernando']. This can be joined just the way you did, resulting in the desired string
' John Maurice Fernando'. For completeness you could add a
.trim() to remove redundant spaces.
const nameparts = this.props.context.pageContext.user.displayName.split(/,/).reverse().join(" ").trim();