您的位置:首页 > Web前端 > JavaScript

【JavaScript】正则表达式--String.replace()变量替换的一点笔记

2016-06-15 22:20 756 查看
1234
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 parameterThe replacement string can include the following special replacement patterns:
PatternInserts
$$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.
$nWhere 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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: