By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
440,812 Members | 863 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 440,812 IT Pros & Developers. It's quick & easy.

trim() and " "

P: n/a
Hi All,

I am using the following trim function:

function trim (str) {
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?

Rob
:)

Nov 7 '05 #1
Share this Question
Share on Google+
12 Replies


P: n/a
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(/(&nbsp;)|(&ensp;)|(&emsp;)/g, ' ');
}

</script>

<p onclick="
alert('x'+trim(getTextContent(this))+'x');
">&nbsp;&nbsp;&nbsp;here&nbsp;is&nbsp;the&nbsp;tex t&nbsp;&nbsp;</p>

--
Rob
Nov 7 '05 #2

P: n/a
RobG wrote:
[...]

Another (probably impractical) idea is don't use &nbsp; - use  
instead.


Actually that doesn't help, IE converts it to &nbsp; anyway.

I also played with other HTML space entities such as en-space '&ensp;'
and em-space '&emsp;'. While IE displays them in the page OK, the
innerHTML property doesn't seem to know what to do with them - they
can't be removed using a regular expression. Only innerText seems to
work reliably.

Using   and   didn't help.

Firefox is happy to use either textContent or innerHTML with a regular
expression.

Likely other browsers will behave differently...

[...]
--
Rob
Nov 7 '05 #3

P: n/a

RobG wrote:
[...]


Thank you for your responses RobG.. I will work on this tomorrow. :)

Rob
:)

Nov 7 '05 #4

P: n/a

RobG wrote:

A simple solution is:

function trim (str)
{
return
str.replace(/^[\s(&nbsp;)]+/g,'').replace(/[\s(&nbsp;)]+$/g,'');
}


Hi Rob. Don't know if you intended this, but when I test the pattern
[\s(&nbsp;)]+ effectively the () no longer function as a sub-pattern.
So it will match &nbsp; and "&" alone, "n" alone, "b" alone etc.

However, I note that your other comments do refer to a character
reference string. I.e.

/&nbsp;/;

Also another solution could be removing the A0 (i.e. 160) char from a
String (if the OP is not talking about mark-up)

/^(\s|\xA0)/;

Julian

Nov 7 '05 #5

P: n/a
RobG wrote:
A simple solution is[...]
not:
function trim (str)
{
return
str.replace(/^[\s(&nbsp;)]+/g,'').replace(/[\s(&nbsp;)]+$/g,'');
}


because it id not supposed to work if you understood character classes.
The above will replace _character_ occurrences of adjacent whitespace,
'(', '&', 'n', ... and ')'.

However, since the &nbsp; entity refers to the character entitity
reference   in HTML, one can use

function trim(str)
{
return
str.replace(/^[\s\xA0]+/g,'').replace(/[\s(&nbsp;)]+$/g,'');
// or \u00A0 for that matter
}
PointedEars
Nov 7 '05 #6

P: n/a
Julian Turner wrote:
Also another solution could be removing the A0 (i.e. 160) char from a
String (if the OP is not talking about mark-up)

/^(\s|\xA0)/;


There is no need for alternation here, character classes will do.
Furthermore, your "solution" removes only _one_ whitespace or
non-breaking from the beginning of the string.
PointedEars
Nov 7 '05 #7

P: n/a

Thomas 'PointedEars' Lahn wrote:
Julian Turner wrote:
Also another solution could be removing the A0 (i.e. 160) char from a
String (if the OP is not talking about mark-up)

/^(\s|\xA0)/;


There is no need for alternation here, character classes will do.
Furthermore, your "solution" removes only _one_ whitespace or
non-breaking from the beginning of the string.


Ah yes, thank you. I was just trying to distinguish removing the
character reference from removing the character itself. I omitted the
Kleen star * by mistake.

Julian

Nov 7 '05 #8

P: n/a
Julian Turner wrote:
Thomas 'PointedEars' Lahn wrote:
Julian Turner wrote:
> Also another solution could be removing the A0 (i.e. 160) char from a
> String (if the OP is not talking about mark-up)
>
> /^(\s|\xA0)/;


There is no need for alternation here, character classes will do.
Furthermore, your "solution" removes only _one_ whitespace or
non-breaking from the beginning of the string.


Ah yes, thank you. I was just trying to distinguish removing the
character reference from removing the character itself. I omitted the
Kleen star * by mistake.


The "_Kleene_ star", or here more precisely the `*' quantifier (zero
or more occurrences of the previous pattern), will perform useless
and potentially harmful replacements as any pattern it is applied to
results in a Regular Expression that also matches the empty string.[1]

"123456".replace(/x*/g, "_") // returns "_1_2_3_4_5_6_"

You were looking for the `+' quantifier (one or more occurrences of
the previous pattern) instead.
PointedEars
___________
[1] <http://en.wikipedia.org/wiki/Kleene_star>
Nov 7 '05 #9

P: n/a

Thomas 'PointedEars' Lahn wrote:
function trim(str)
{
return
str.replace(/^[\s\xA0]+/g,'').replace(/[\s(&nbsp;)]+$/g,'');
// or \u00A0 for that matter
}
PointedEars


I take your point on character classes as well. Did you mean "*" or
"+". Some further adaptation:-

function trimWS(str)
{
return str.replace(/^[\s\xA0]*/g,"").replace(/[\s\xA0]*$/g,"");
}

function trimWSCharEntity(str)
{
return
str.replace(/^(\s|&nbsp;)*/g,"").replace(/(\s|&nbsp;)*$/g,"");
}

Julian

Nov 7 '05 #10

P: n/a

Thomas 'PointedEars' Lahn wrote:
The "_Kleene_ star", or here more precisely the `*' quantifier (zero
or more occurrences of the previous pattern), will perform useless
and potentially harmful replacements as any pattern it is applied to
results in a Regular Expression that also matches the empty string.[1]

"123456".replace(/x*/g, "_") // returns "_1_2_3_4_5_6_"

You were looking for the `+' quantifier (one or more occurrences of
the previous pattern) instead.


Good point. Ignore my other comments in this thread. Although given
that the OP is using ^(start of input) and $(end of input) this could
prevent the more adverse effects of *quanitifier. However your point
is well made, there is no reason not to use the "+" quantifier here.

Julian

Nov 7 '05 #11

P: n/a
Julian Turner wrote:
Thomas 'PointedEars' Lahn wrote:
function trim(str)
{
return
str.replace(/^[\s\xA0]+/g,'').replace(/[\s(&nbsp;)]+$/g,'');
// or \u00A0 for that matter
}
[...]

Please don't cite signatures (of any kind) unless you explicitely refer
to them.
I take your point on character classes as well. Did you mean "*" or
"+".
The latter, see <30****************@PointedEars.de>.
Some further adaptation:-

function trimWS(str)
{
return str.replace(/^[\s\xA0]*/g,"").replace(/[\s\xA0]*$/g,"");
}
There is no advantage in that "adaptation", but the disadvantage
of reduction of efficiency. Instead use the above or

function trimWS(str)
{
return str.replace(/^[\s\xA0]*(.*[^\s\xA0])[\s\xA0]*$/g, "$1");
}
function trimWSCharEntity(str)
{
return str.replace(/^(\s|&nbsp;)*/g,"").replace(/(\s|&nbsp;)*$/g,"");
}


function trimWSCharEntity(str)
{
return (
str.replace(/^(\s|&nbsp;)+/g, "").replace(/(\s|&nbsp;)+$/g, ""));
}

and I think there should be a one-call solution with Negative Lookahead,
but probably not really nicer than the former.
PointedEars
Nov 7 '05 #12

P: n/a

Thomas 'PointedEars' Lahn wrote:
Julian Turner wrote:
Thomas 'PointedEars' Lahn wrote:
function trim(str)
{
return
str.replace(/^[\s\xA0]+/g,'').replace(/[\s(&nbsp;)]+$/g,'');
// or \u00A0 for that matter
}
[...]


Please don't cite signatures (of any kind) unless you explicitely refer
to them.
I take your point on character classes as well. Did you mean "*" or
"+".


The latter, see <30****************@PointedEars.de>.
Some further adaptation:-

function trimWS(str)
{
return str.replace(/^[\s\xA0]*/g,"").replace(/[\s\xA0]*$/g,"");
}


There is no advantage in that "adaptation", but the disadvantage
of reduction of efficiency. Instead use the above or

function trimWS(str)
{
return str.replace(/^[\s\xA0]*(.*[^\s\xA0])[\s\xA0]*$/g, "$1");
}
function trimWSCharEntity(str)
{
return str.replace(/^(\s|&nbsp;)*/g,"").replace(/(\s|&nbsp;)*$/g,"");
}


function trimWSCharEntity(str)
{
return (
str.replace(/^(\s|&nbsp;)+/g, "").replace(/(\s|&nbsp;)+$/g, ""));
}

and I think there should be a one-call solution with Negative Lookahead,
but probably not really nicer than the former.
PointedEars


Interesting. I think you are right about the negative lookahead. I
set out some further single expression alternatives below. The
negative lookahead is definitely ugly, and my guess would be slower.

1. White space in strings

ALTNERATE
return str.replace(/^[\s\xA0]+|[\s\xA0]+$/g,"");

NON-GREEDY
return str.replace(/^[\s\xA0]+((a|[^a])*?)[\s\xA0]+$/g,"$1");
2. Markup

ALTERNATE
return str.replace(/^(\s|&nbsp;)+|(\s|&nbsp;)+$/g,"");

NON-GREEDY
return str.replace=(/^(\s|&nbsp;)+((a|[^a])*?)(\s|&nbsp;)+$/;,"$2");

NEGATIVE LOOKAHEAD
return
str.replace=(/^(\s|&nbsp;)+(((a|[^a])(?!(\s|&nbsp;)+$)|([^\s]|&)(?=(\s|&nbsp;)$))*)(\s|&nbsp;)+$/,"$2");

Julian

Nov 7 '05 #13

This discussion thread is closed

Replies have been disabled for this discussion.