Reputation: 623
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 in $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.
Upvotes: 2
Views: 1262
Reputation: 59658
you should be able to do something like this:
newstr = str.replace(re, function(input, match1, match2) {
return match2.toUpperCase() + ', ' + match1;
})
Upvotes: 3
Reputation: 333206
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];
Upvotes: 0
Reputation: 170288
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
Upvotes: 1