以下代碼是在一段字符串中,用正則表達式找到數字,使用 replace() 方法,用找到的數字的兩倍值替換原數字。replace() 方法的第二個參數為一個函數,返回找到數字的兩倍值。
<script>
var str="去年是2014年,今年是2015年";
var newStr=str.replace(/\d+/g, function () {
//調用方法時內部會產生 this 和 arguments console.log(arguments[0]);
//查找數字后,可以對數字進行其他操作 return arguments[0] * 2; });
console.log(newStr);
</script>
正則表達式 /\d+/g: 匹配至少一個數字。
調用函數時內部會生成 arguments,console.log(arguments); 的結果:
需要取得的是數字 2014 和 2015,所以只要取得 arguments[0] 即可。
console.log(arguments[0]); 的結果:
最終結果得到:" 去年是4028年,今年是4030年 "
查找數字后,也可以對數字進行其他操作