tag:blogger.com,1999:blog-3930375442497799514.post-23080187377183261082008-06-10T14:33:00.000-07:002008-06-10T14:56:39.607-07:002008-06-10T14:56:39.607-07:00JavaScript endsWith() and trim()Today I needed a new JavaScript string function to see if the end of a string matched something. In ASP.NET, when controls within other controls get written as HTML, the id's get prepended with a bunch of junk from the container controls. So, for your JavaScript functions to find a particular control, it's useful to use document.getElementsByTagName('input') for example to get a list of input tags, then iterate the list testing the end of the id attribute to find a particular control. Anyway, I used 'prototype' to add an endsWith(x) function to strings.
Here it is. I hope you find it useful.<blockquote><pre>
String.prototype.endsWith = function(txt,ignoreCase)
{
var rgx;
if(ignoreCase)
{
rgx = new RegExp(txt+"$","i");
}
else
{
rgx = new RegExp(txt+"$");
}
return this.match(rgx)!=null;
}
</pre></blockquote>For example: 'hello'.endsWith('LO',true) returns true. Notice I passed in a true value for the ignoreCase parameter.
Or with a variable: var x = 'goodbye'; then x.endsWith('bye') returns true.
While I'm here, here's a cool one liner that will do a trim() on both sides of a string.
<blockquote><pre>String.prototype.trim = function()
{
return this.replace(/(^\s*|\s*$)/g,'');
}
</pre></blockquote>For example: alert('.' + ' blah '.trim() + '.'); shows ".blah."Tom Puleohttp://www.blogger.com/profile/10697521511530638404noreply@blogger.com0