I am trying to show displayname from AAD using in my spfx but for the full name i cannot get the array of first item. I know i am missing something from below but couldn't analyse what's missing.

Example: Name: Fernando, John Maurice, First Name: John Maurice, Last Name: Fernando

From below code output what i get is "Maurice John Fernando", But what i want is "John Maurice Fernando"

 const nameparts = this.props.context.pageContext.user.displayName.split(/,|\s/).reverse().join(" ") 

Your question isn't really a SharePoint related question, but more of a Javascript/Regex question. But I'll try to help you out:

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 /,|\s/. This splits the string on each occurence of a , or (|) a space \s.

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 split(): ['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(); 
  • Thank you Mark, it works Perfect !
    – striker92
    Oct 13 '21 at 8:26
  • Great to hear! Could you mark my answer as the answer to your question? Thanks! Oct 13 '21 at 8:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.