开发者

Manipulating JavaScript's parenthesized substring matches

开发者 https://www.devze.com 2022-12-10 02:18 出处:网络
Example taken from Mozilla\'s help page <script type="text/javascript"> re = /(\\w+)\\s(\\w+)/;

Example taken from Mozilla's help page

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

Is it possible to further manipulate the substring match directly in any way? Is there any way to, for example, capitalize just the word Smith in one line here? Can I pass the value i开发者_如何学编程n $2 to a function that capitalizes and returns a value and then use it directly here?

And if not possible in one line, is there an easy solution to turn "John Smith" into "SMITH, John"?

Trying to figure this out but not coming up with the right syntax.


you should be able to do something like this:

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


No, that (a one-liner) is not possible using JavaScript's RegExp object. Try:

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

Output:

SMITH, John


You could simply extract the matched substrings and manipulate them yourself:

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

精彩评论

暂无评论...
验证码 换一张
取 消