Robert Mark Bram wrote:
Hi All,
I am using the following trim function:
function trim (str) {
return str.replace(/^\s*/g, '').replace(/\s*$/g, '');
Not that it makes any practical difference that I can tell, but
shouldn't the match be for one or more, not zero or more?
return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
The problem is that this doesn't trim instances of the " " char -
the non breaking space. Can this be represented in a grep statement at
all?
Presumably you are using this with innerHTML. Depending on your use of
the trim function, you should probably ensure that you pass it a string
of plain text without HTML entities.
You can do that by getting the element text using textContent (DOM 3
browsers) or innerText (IE) so that you pass text, not HTML markup, to
trim(). Not all browsers support one or the other, those will need
parsed innerHTML.
Another (probably impractical) idea is don't use - use
instead.
A simple solution is:
function trim (str)
{
return
str.replace(/^[\s( )]+/g,'').replace(/[\s( )]+$/g,'');
}
A textContent/innerText alternative might be:
function trim (str)
{
return str.replace(/^\s+/g, '').replace(/\s+$/g, '');
}
function getTextContent (el)
{
if (el.textContent) return el.textContent;
if (el.innerText) return el.innerText;
if (el.innerHTML) return el.innerHTML.replace(/ /g,' ');
return null;
}
And your call may be:
var trimmedText = trim( getTextContent(elementReference) ) ;
The replacement regular expression in the innerHTML fork can be extended
to remove all other markup if required (and hence more closely emulate
textContent/innerText), there are also other HTML entities you might
want to consider:
<URL:http://www.w3.org/TR/html4/sgml/entities.html#h-24.3.1>
Taking it further, there are other markup languages such as MathML which
have a number of entities that represent space (there may be more than
those listed below):
U000A0, NO-BREAK SPACE nbsp, NonBreakingSpace
U02002, EN SPACE ensp
U02003, EM SPACE emsp
U02004, THREE-PER-EM SPACE emsp13
U02005, FOUR-PER-EM SPACE emsp14
U02007, FIGURE SPACE numsp
U02008, PUNCTUATION SPACE puncsp
U02009, THIN SPACE ThinSpace, thinsp
U02009-0200A-0200A, space of width 5/18 em ThickSpace
U0200A, HAIR SPACE hairsp, VeryThinSpace
U0200B, ZERO WIDTH SPACE ZeroWidthSpace,
NegativeVeryThinSpace,
NegativeThinSpace,
NegativeMediumSpace,
NegativeThickSpace
<URL:http://www.w3.org/TR/MathML2/bycodes.html>
Support for these varies, it may not be worth worrying about (yet).
Play code:
<script type="text/javascript">
function trim (str)
{
return str.replace(/^\s*/g, '').replace(/\s*$/g, '');
}
function getTextContent (el)
{
if (el.textContent) return el.textContent;
if (el.innerText) return el.innerText;
if (el.innerHTML) return
el.innerHTML.replace(/( )|( )|( )/g, ' ');
}
</script>
<p onclick="
alert('x'+trim(getTextContent(this))+'x');
"> here is the tex t </p>
--
Rob