I’m creating my own jquery plugin to format phone numbers.
Here are a few spans with some demo data.
<span class="formatMe"> </span><br />
<span class="formatMe">(123)456-7890</span><br />
<span class="formatMe"> </span><br />
<span class="formatMe"></span><br />
<span class="formatMe">(123)456-7890</span><br />
My problems happen with a span containing the
I figure I’d simply .trim() the values inside each element, which would take care of the white space, but I’m not getting the desired result of nothing.
<script>
(function( $ ){
$.fn.voip1Wire = function() {
return this.each(function() {
var theValue = $(this).html().trim().replace(/ /g,'');
if (theValue === null || theValue === undefined || theValue == ""){
$(this).html("------");
return true; // break out of the loop
}
$(this).html('formatted number to return');
}); // eof .each
};
})( jQuery );
</script>
It may be overkill, you can see I’m using the .trim() and .replace()
var theValue = $(this).html().trim().replace(/ /g,'');
I’m probably not using javascript/jquery correctly, but here is what I have:
formatted number to return
formatted number to return
formatted number to return
-----------
formatted number to return
I expected the 1st and 3rd to return the dashes. So I’m baffled at the whitespace trimming.
Anyone see what I’m doing wrong?
The problem here is that
.html()will return the characters when they’re present in the HTML, which is not white space per se.The DOM parser will interpret that sequence of characters as white space, but those characters inside of a regular string (which is what
.html()returns) is not considered white space.Assuming that the spans contain only text, you can replace
.html()by.text()to retrieve thetextNode(s) which will be trimmed properly:Fiddle
Also as noted by @undefined, the native
String.trim()is not implemented in IE8 and below, sojQuery.trim()is preferred if you want to support those versions:Fiddle
Now if you want to stick to a regex solution:
Fiddle
Small note:
if (theValue === "")should suffice after the regex replace as span elements always return a string for.html()(which the.replace()works upon), there’s no need to check fornull/undefined.