# Parsing "mailto:"

Can you help me to review my "mailto:"-parsing function ?

Since I'm trying to write less code, that is as simple as possible.

I'm not sure there if there is some bug or better solution.

var href = 'mailto:hello@world.com?subject=My+Subject&body=My+Body';

function getMailto(s) {
var r = {};
var email = s.match(/mailto:([^\?]*)/);
email = email[1]?email[1]:false;
var subject = s.match(/subject=([^&]+)/);
subject = subject?subject[1].replace(/\+/g,' '):false;
var body = s.match(/body=([^&]+)/);
body = body?body[1].replace(/\+/g,' '):false;

if(email) {r['email'] = email;}
if(subject) {r['subject'] = subject;}
if(body) {r['body'] = body;}

return r;
}

console.log(getMailto(href));


Im not sure there is some bug or better solution.

Like @Domenic said in this answer, parsing URLs is hard, and it's nearly impossible to do it correctly with regexes. Email addresses are also quite complex.

If your function is good enough really depends on your use-case. Most of the bugs described below may not apply, but I would at least fix the first one, which leads to problems with some valid email addresses.

Bugs:

• ? is a valid character for the local part of an email address, but mailto:hel?lo@world.com?subject=My+Subject&body=My+Body breaks your script.
• You decode some URL encoded characters (the +), but not the rest, which seems odd. I would URL decode all characters. Otherwise, you can't have certain characters in your subject/body. Eg: subject=Coffee&Cookies? doesn't work, and subject=Coffee%26Cookies? isn't properly formatted (while subject=Coffee+Cookies? would be properly formatted, which is inconsistent)
• The order of arguments does not matter for URLs. But it does matter for your script, in some corner-cases: mailto:hello@world.com?body=Hi+there+subject=Something&subject=My+Subject
• your script breaks on invalid input such as hello@world.com?body=b&subject=s

Misc

• r and s aren't great variable names.
• more spaces would lead to slightly more readable code, eg around : or ?.
• You are being a bit careless about subject= and body= by failing to ensuring that they are preceded by either a ? or &.
• Strings are to be percent-encoded (Sec 5), which means that you should do percent-decoding. If this code is to be run in a browser, you can use decodeURIComponent.
• Spaces are supposed to be encoded as %20 rather than as + (Sec 5). The spec acknowledges that using + to mean Space does occur in practice, though.
In addition to the spec violations, I would say that the use of false rather than null to mean the absence of a property is weird.