作者:Dfsk刘海_368 | 来源:互联网 | 2023-09-24 17:43
篇首语:本文由编程笔记#小编为大家整理,主要介绍了JavaScript正则表达式--String.replace()变量替换的一点笔记相关的知识,希望对你有一定的参考价值。
篇首语:本文由编程笔记#小编为大家整理,主要介绍了Javascript正则表达式--String.replace()变量替换的一点笔记相关的知识,希望对你有一定的参考价值。
1 2 3 4
| var re = /(\\w+)\\s(\\w+)/; var str = 'John Smith'; var newstr = str.replace(re, '$2, $1'); console.log(newstr);
|
$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. |
$&#96; | 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. |
Switching words in a string
About Sodino