2009-11-04 51 views
2

取自Mozilla's help page的示例操縱JavaScript的括號子串匹配

<script type="text/javascript"> 
    re = /(\w+)\s(\w+)/; 
    str = "John Smith"; 
    newstr = str.replace(re, "$2, $1"); 
    document.write(newstr); 
</script> 

是否可以以任何方式直接進一步操縱子串匹配?有沒有辦法,例如,在這裏只用一行中的史密斯這個詞?我可以將$ 2中的值傳遞給大寫並返回值的函數,然後直接在此處使用它嗎?

如果不可能在一行中,是否有一個簡單的解決方案將「John Smith」變成「SMITH,John」?

試圖解決這個問題,但沒有提出正確的語法。

+0

不是su如果它是一個安全或實現的東西,但是子串匹配即使在通過其他方法連接和處理時也不會被篡改。這個:'newstr = str.replace(re,('$ 2'+'forgreatjustice')。toUpperCase()+',$ 1');'''SmithFORGREATJUSTICE,'' – 2015-01-29 20:48:37

回答

3

,你應該能夠做這樣的事情:

newstr = str.replace(re, function(input, match1, match2) { 
    return match2.toUpperCase() + ', ' + match1; 
}) 
1

不,使用JavaScript的RegExp對象無法實現(單行)。 嘗試:

str = "John Smith"; 
tokens = str.split(" "); 
document.write(tokens[1].toUpperCase()+", "+tokens[0]); 

輸出:

SMITH, John 
0

你可以簡單地提取匹配子和自己操縱他們:

str = "John Smith"; 
re = /(\w+)\s(\w+)/; 
results = str.match(re); 
newstr = results[2].toUpperCase() + ", " + results[1];