0
我在MDN documentation上遇到了關於在字符串上使用替換方法的示例。在javascript中使用正則表達式的String.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的順序時,它應該是'ohn Smith,J`。但事實並非如此。
是我對$ 1和$ 2的理解(子字符串匹配正確)以及爲什麼newstr1不同?
感謝您的意見