Reputation: 43
How can I reverse the order of Duck, Donald with Javascript?
I am currently retrieving Duck, Donald from a query string and I would like to be able to display it on the page, receiving it as Dondald Duck.
I am using document.write("Name: " + Request.QueryString("name"));
to write Duck, Donald to the page and I would also like to be able to change 'Mouse', 'Mickey G' to just 'Mickey Mouse'.
Upvotes: 1
Views: 1699
Reputation: 9382
var name = Request.QueryString("name").Item(1).split(",").reverse().join(" ").trim();
if(name.split(" ").length > 2) {
name = name.split(" ");
name.splice(1, 1);
name = name.join(" ");
}
document.write(name);
Example at http://jsfiddle.net/6AdGs/
Upvotes: 3
Reputation: 75
As above, but consider: Are first names and surnames always separated by commas? It becomes relevant with some non-English names you may find like 'Silva dos Santos, Miguel Jesus', where Silva dos Santos are the family names and Miguel Jesus are given names.
Upvotes: 1
Reputation: 738
This function may help you.
<script>
function reverseName(str) {
var tail = str.substr(0, str.indexOf(","));
var head = str.substr(str.indexOf(",") + 1);
return head + ' ' + tail;
}
document.write("Name: " + reverseName(Request.QueryString("name")));
</script>
Upvotes: 2
Reputation: 8053
You can split the string using split method, and then past them in correct order:
var str = 'Duck, Donald';
var parts = str.split(',');
document.write(parts[1] + ' ' + parts[0]);
Basically thats what you need to do. Hope it helps!
Upvotes: 2