的Javascript替换法澄清
问题描述:
1这是什么$ 3 $ 2 $ 1只表示在:的Javascript替换法澄清
var s = "The quick brown fox jumped over the lazy dog.";
var re = /(\S+)(\s+)(\S+)/g;
// Exchange each pair of words.
var result = s.replace(re, "$3$2$1");
document.write(result);
// Output: quick The fox brown over jumps lazy the dog.
2和$ 0,$ 1,$ 2:
function f2c(s1) {
// Initialize pattern.
var test = /(\d+(\.\d*)?)F\b/g;
// Use a function for the replacement.
var s2 = s1.replace(test,
function($0,$1,$2)
{
return((($1-32) * 5/9) + "C");
}
)
return s2;
}
document.write(f2c("Water freezes at 32F and boils at 212F."));
// Output: Water freezes at 0C and boils at 100C.
注意,感谢您的回复,我明白了数字1,但数字2有点困难,我正在努力解决它。
感谢,
优素福
答
它代表了括号内的群体。 $1
是由第一个(\S+)
匹配的表达式,$2
是由(\s+)
匹配的表达式,$3
是最后一个组匹配的表达式。
答
在正则表达式中,一组括号指示引擎创建反向引用。然后将其存储起来供您稍后使用,例如用于替换。后面的参考文献编号为1,2,3等。在你的情况下,$1
指的是第一个\S+
,$ 2指的是\s+
和$ 3指的是最后的\S+
。
这里,\S+
匹配任何不是空白和空白\s+
,所以我预计这方面的问题有$1
等于The
,$2
= (空间)和
$3
= quick
。替换时,通过以与原始文件不同的顺序使用反向引用,您实质上可以交换The
和quick
。
[Submatch replacement pattern](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace#Specifying_a_string_as_a_parameter)。 – 2014-09-23 14:54:45