[英]String.replace method in javascript using regex
我在MDN文檔中遇到了關於在字符串上使用replace方法的這個例子。
這是那里引用的例子
var re = /(\w+)\s(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$2, $1");
print(newstr);//Smith,John
我將正則表達式更改為以下內容並進行了測試。
var re = /(\w?)(\w+)/;
var str = "John Smith";
var newstr = str.replace(re, "$1, $1");
newstr;//J, ohn Smith
var newstr1=str.replace(re,"$2, $1");
newstr1;//ohn, J Smith.
在此示例中,$ 1必須是J
,$ 2必須是ohn Smith
。 當我為newstr1顛倒$ n的順序時,它應該是'ohn Smith,J`。 但事實並非如此。
是我對1美元和2美元的理解(子串匹配正確)以及為什么newstr1不同?
感謝您的評論
實際上, $1
是"J"
, $2
是"ohn"
而" Smith"
是無與倫比的。
var re = /(\w?)(\w+)/,
str = "John Smith";
str.replace(re, function (match, $1, $2) {
console.log('match', match);
console.log('$1', $1);
console.log('$2', $2);
return ''; // leave only unmatched
});
/* match John
$1 J
$2 ohn
" Smith"
*/
因此,你的交換是用ohn
轉換J
,給你newstr1
。
為什么會這樣? 因為\\w
匹配一個單詞 ,但是?
使它成為可選項,所以就像(.*?)(.)
在$1
捕獲一個字母一樣, (\\w?)
也是這樣做的。 第二捕獲, (\\w+)
然后只能擴展到字結束時,dispite的+
,因為\\w
不匹配空白\\s
。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.