[Solved] Javascript replacing characters using replace() [duplicate]


Refer to the link in the comment I posted above to learn about regular expressions.
But to explain to you what the code you posted actually does…

var re = /(\w+)\s(\w+)/; is a regular expression. the leading and trailing / are delimiters and don’t actually have anything to do with the replacement going on other than telling the interpreter what the actual expression is: (\w+)\s(\w+)

  • The () are called capturing parenthesis, and are remembered by the browser so that they can be used later in the replacement. The first set is assigned to $1, the second to $2, etc…

  • \w matches any alphanumeric character including the underscore. It’s equivalent to [A-Za-z0-9_]

  • + means apply the previous expression one or more times

  • \s matches a single whitespace character

So your expression says look at the string "zara ali" for one or more alphanumeric characters (and remember them as a group, storing them in $1), then a white space character, then another group of one or more alphanumeric characters (and remember them as a group, storing them in $2). If a match is made, replace the string with the string "$2, $1", which is really the second capturing group, followed by a comma and a space, ending with the first capturing group.

So you start with: "zara ali" and end with "ali, zara"

solved Javascript replacing characters using replace() [duplicate]