1
2
3
4
|
var re =
/(\w+)\s(\w+)/;
var str =
'John Smith';
var newstr = str.replace(re,
'$2, $1');
console.log(newstr);
// Smith, John
|
$1
$2
是指被括号()
包起来的\w+
。
即当要使用变量替换时,$n
指第n个用()
包起来的表达式的值。
要用()
包起来呀…‘(>﹏<)′ ‘(>﹏<)′
Specifying a string as a parameter
The replacement string can include the following special replacement patterns:
Pattern | Inserts |
---|---|
$$ | Inserts a “$”. |
$& | Inserts the matched substring. |
$` | Inserts the portion of the string that precedes the matched substring. |
$’ | Inserts the portion of the string that follows the matched substring. |
$n | Where n is a non-negative integer lesser than 100, inserts the nth parenthesized submatch string, provided the first argument was a RegExp object. |