You*_*sef 0 javascript replace
1- $ 3 $ 2 $ 1的含义是:
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.
Run Code Online (Sandbox Code Playgroud)
2-和$ 0,$ 1,$ 2 in:
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.
Run Code Online (Sandbox Code Playgroud)
请注意,感谢您的回复,我理解第1号,但是第2号有点难,我正在努力解决它.
谢谢,
优素福
1-在reg exp中,括号表示捕获模式,$ X表示对捕获元素的引用:
var re = /(\S+)(\s+)(\S+)/g;
^ ^ ^
| | |
$1 $2 $3
Run Code Online (Sandbox Code Playgroud)
在这种模式中,替换它将$1$2$3采取3个匹配并反转它们,所以它将采取"快速"并将其变为"快速".
2- $ 0引用整个匹配的子表达式.给定的函数不会使用$ 0或$ 2,只需$ 1即可将°F转换为C°
| 归档时间: |
|
| 查看次数: |
218 次 |
| 最近记录: |