regex - Javascript replacing characters using replace() -
this question has answer here:
- javascript replace method, replace “$1” 2 answers
i have piece of code
<html> <head> <title>javascript string replace() method</title> </head> <body> <script type="text/javascript"> var re = /(\w+)\s(\w+)/; var str = "zara ali"; var newstr = str.replace(re, "$2, $1"); document.write(newstr); </script> </body> </html> can explain please , how it's read?
var re = /(\w+)\s(\w+)/; also in str.replace(re, "$2,$1); , $2 & $1?
refer link in comment posted above learn regular expressions. explain code posted does...
var re = /(\w+)\s(\w+)/; regular expression. leading , trailing / delimiters , don't have replacement going on other telling interpreter actual expression is: (\w+)\s(\w+)
the
()called capturing parenthesis, , remembered browser can used later in replacement. first set assigned $1, second $2, etc...\wmatches alphanumeric character including underscore. it's equivalent [a-za-z0-9_]+means apply previous expression 1 or more times\smatches single whitespace character
so expression says @ string "zara ali" 1 or more alphanumeric characters (and remember them group, storing them in $1), white space character, group of 1 or more alphanumeric characters (and remember them group, storing them in $2). if match made, replace string string "$2, $1", second capturing group, followed comma , space, ending first capturing group.
so start with: "zara ali" , end "ali, zara"
Comments
Post a Comment