RegEx - Find and Replace with Variables

Well, this was broken down in the jsfiddle that I created for you, but to break it down further, try this:

  • draft.content is the content of your draft.
  • draft.content.match() is a function to look for a match in your draft content.
  • draft.content.match(/([M][r-s]\.\s)(\w*\s)(\w*)/) is a function to look for a match in your draft content matching the regular expression you provided at the beginning, but without the ‘g’ modifier for the reason I gave earlier.
    • I’m assuming at this point I don’t need to explain how the regular expression is defined as you are already using it and some things you wrote earlier suggest you might have an idea about that.
  • In JavaScript the square brackets indicate an array index.
    • If you don’t know what an array is, think of it as an ordered list.
  • draft.content.match(/([M][r-s]\.\s)(\w*\s)(\w*)/)[3] is a function to look for a match in your draft content matching the regular expression provided, and return the third element of the match.
    • The first element is the title.
    • The second element is the forename.
    • The third element is the surname, hence we want the third matched element.
    • JavaScript arrays are zero indexed, but the 0 index is populated with the entire match, the elements relate to the groups.
1 Like