2009-11-04 47 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];