defaulting String values

0 views
Skip to first unread message

Bill Burcham

unread,
Nov 20, 2009, 10:25:08 AM11/20/09
to Portland JavaScript Admirers
What is the JavaScript idiom for a String expression that:

returns the String if one is provided and it is neither blank nor
whitespace only
otherwise returns some default string (provided to the expression)

I wrote this to get me by (vod == "value or default"):

function vod( val, def) {
// handles null, empty string and whitespace string
if( ! val || ! val.trim() ) {
return def;
}
else {
return val;
}
}

But I'm not particularly happy with it. But it does let me write stuff
like:

vod( $('input[name="map_widget[zoom]"]').val(), '8')

Which will result in either the input value or '8'.

Jesse Hallett

unread,
Nov 20, 2009, 1:04:55 PM11/20/09
to pd...@googlegroups.com

You can do something similar to the Ruby idiom, though without the `blank?` method:

    str && !str.match(/^\s+$/) ? str : 'default'

You could also define blank as a helper function rather than a method:

    function isBlank(val) {
        return !val || val.match(/^\s+$/);
    }

Things get simpler if you are not worried about whitespace-only strings because the empty string is falsy in JavaScript:

    str ? str : 'default'


--

You received this message because you are subscribed to the Google Groups "Portland JavaScript Admirers" group.
To post to this group, send email to pd...@googlegroups.com.
To unsubscribe from this group, send email to pdxjs+un...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/pdxjs?hl=.


Bill Burcham

unread,
Nov 20, 2009, 1:33:02 PM11/20/09
to Portland JavaScript Admirers
Yeah empty string is falsy but blank string is not falsy. Right?

Also FYI I just learned that val.trim() seems to work in late model
Firefox, WebKit, Chrome but not in e.g. Safari Version 4.0.3 (6531.9).

I don't know where I am getting trim in those newer browsers but I
certainly don't get it at all in that older one. So since I'm using
jQuery I changed my call to $.trim(val) and that works everywhere.
Phooey on hygiene.

Duncan Beevers

unread,
Nov 20, 2009, 2:17:04 PM11/20/09
to pd...@googlegroups.com
Or even simpler.

str || 'default'

Bill Burcham

unread,
Nov 20, 2009, 4:47:11 PM11/20/09
to pd...@googlegroups.com
Ya that's clean but still doesn't handle str = '    '; // (blanks)

Could do (in jQuery):

$.trim( str ) || 'default'

Matt Youell

unread,
Nov 20, 2009, 5:15:09 PM11/20/09
to Portland JavaScript Admirers
Must these two operations happen together (trim and default
selection)?

Mike Leach

unread,
Nov 23, 2009, 4:02:50 PM11/23/09
to pd...@googlegroups.com
Some browsers may not support this, but HTML can be extended with a custom attribute for defining a default value that is accessed via jQuery attr().

<input id="Company" type="text" defValue="[not provided]" />

<script type="text/javascript">
$(function() {
$("#submitButton").click(function () {
if( $('#Company').val() ){
alert( $('#Company').val() );
}
else{
alert('Default value = ' + $('#Company').attr('defValue') );
}
});
});
</script>

--

You received this message because you are subscribed to the Google Groups "Portland JavaScript Admirers" group.
To post to this group, send email to pd...@googlegroups.com.
To unsubscribe from this group, send email to pdxjs+un...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/pdxjs?hl=.


Bill Burcham

unread,
Dec 15, 2009, 6:15:56 PM12/15/09
to pd...@googlegroups.com
Well if you're using XHTML, since it's XML, you can define any attributes you want so long as you qualify them as belonging to a separate (non-HTML) namespace like this:

<input id="Company" type="text" defaults:value="[not provided]" />

(I used a hypothetical XML namespace called defaults) All browsers supporting XHTML should support that syntax just fine.

Mike Leach

unread,
Dec 15, 2009, 6:21:48 PM12/15/09
to pd...@googlegroups.com
I personally wouldn't defer to the W3C specs. XHTML is all but dead in HTML5.

Just trust JQuery to do the ugly cross-browser DOM work (even with a a plain old HTML DOCTYPE, this still works).

--

You received this message because you are subscribed to the Google Groups "Portland JavaScript Admirers" group.
To post to this group, send email to pd...@googlegroups.com.
To unsubscribe from this group, send email to pdxjs+un...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/pdxjs?hl=en.

Jesse Hallett

unread,
Dec 15, 2009, 10:30:59 PM12/15/09
to pd...@googlegroups.com
If you want an option that is valid as HTML 5 and that does not
require XHTML, here is an option:

<input id="Company" type="text" data-default-value="[not provided]" />

You can use any attribute name prefixed with 'data-' to embed custom
attributes. It is basically a poor man's XML namespacing.
http://ejohn.org/blog/html-5-data-attributes/

Bill Burcham

unread,
Dec 16, 2009, 9:42:41 AM12/16/09
to pd...@googlegroups.com
Oh wow Jesse. The comments on that thread were fascinating.

Mike: is it really true that XML serialization is going to be dropped from HTML 5? As you alluded, it is part of the "spec". (and oy, what a spec) Is there any concise record of the "inside baseball" going on around this? I took a peek at some of the HTML WG's minutes and stuff and it's all bleep-blop.

I just took a peek at an old XHTML namespace test I wrote and it looks like (in Firefox/Chrome/Safari) browser support hasn't progressed much in the past few years, which would support Mike's assertion.

Bill Burcham

unread,
Dec 16, 2009, 9:53:32 AM12/16/09
to pd...@googlegroups.com
The W3C FAQ on the Future of XHTML from June, 2009 kind of makes it sound like as of June at least, their plan was that HTML 5 would be XML (have an "XML serialization" option).

However, that FAQ cites Issue 41 "Decentralized Extensibility", which supports Mike's assessment (XML is out). In that note Sam Ruby asks for XML (and XML namespace) support for stuff like SVG, MathML (implying those foreign namespaces are currently incompatible with HTML 5).

Jesse Hallett

unread,
Dec 16, 2009, 1:38:49 PM12/16/09
to pd...@googlegroups.com

In terms of browser support, you have to make sure you are serving pages with an XML mime type.  I think the correct one is 'application/xml+xhtml'.  It seems that most people are serving pages with an XHTML doctype but with 'text/html' as the mime type.  So they are actually serving plain old HTML 4 or 5, depending on the browser, but do not realize it.  I think this is part of why HTML 5 will be a return to "tag soup".

As I understand it HTML 5 will support an optional XML mode.  But there won't be much reason to use it unless you are a purist.  The XML mode won't add any particular features; and XML documents won't render in IE in general.

I have not read the spec.  So I may be a little off in my understanding.  I have mainly been reading others' summaries from the blogosphere.  You might try looking up the HTML 5 Doctor for more information.  And there are other resources out there.

On Dec 16, 2009 6:53 AM, "Bill Burcham" <bill.b...@gmail.com> wrote:

The W3C FAQ on the Future of XHTML from June, 2009 kind of makes it sound like as of June at least, their plan was that HTML 5 would be XML (have an "XML serialization" option).

However, that FAQ cites Issue 41 "Decentralized Extensibility", which supports Mike's assessment (XML is out). In that note Sam Ruby asks for XML (and XML namespace) support for stuff like SVG, MathML (implying those foreign namespaces are currently incompatible with HTML 5).

-- You received this message because you are subscribed to the Google Groups "Portland JavaScript...

Mike Leach

unread,
Dec 16, 2009, 1:54:40 PM12/16/09
to pd...@googlegroups.com
That data attribute prefix looks pretty slick. Can't wait to litter my code with custom semantics.

The HTML5 steering committee is wisely acknowledging the vast amounts of SGML code in the wild that looks like:

<ul>
<li>Item 1
<li>Item 2
</ul>
<br>

Most browser engines could parse this from day 1. XHTML compliance rarely had the end user and casual developer in mind. HTML 5 puts the pressure back on the parsers where it belongs (not on the coders).

Given the need for less verbosity in scripting, I actually prefer this style. I also refuse to stop using <b/> and <i/> :P

-Mike

--

You received this message because you are subscribed to the Google Groups "Portland JavaScript Admirers" group.

To post to this group, send email to pd...@googlegroups.com.
To unsubscribe from this group, send email to pdxjs+un...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/pdxjs?hl=en.
Reply all
Reply to author
Forward
0 new messages