473,385 Members | 2,210 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,385 software developers and data experts.

trim() and " "

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
12 47407
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
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

RobG wrote:
[...]


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

Rob
:)

Nov 7 '05 #4

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
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
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

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
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

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

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
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

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 thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
by: ian justice | last post by:
Before i post actual code, as i need a speedyish reply. Can i first ask if anyone knows off the top of their head, if there is a likely obvious cause to the following problem. For the moment i've...
14
by: tertius | last post by:
Is there a better way to append certain chars in a string with a backslash that the example below? chr = "#$%^&_{}" # special chars to look out for str = "123 45^ & 00 0_" # string to...
13
by: rbronson1976 | last post by:
Hi all, I have a very simple page that Firefox has problems with: www.absolutejava.com/testing.htm First of all, this page seems to be perfectly valid XHTML Strict. Both the W3C validator as...
5
by: Naveen K Kohli | last post by:
I am try to set the text of the drop down list item as ListItem li = new ListItem(); li.Text = "&nbsp;"+"MyValue"; myDropDown.Items.Add("li); The intent is to add a spacing in front of the...
0
by: K B | last post by:
Hi again, I have a gridview, when I get the selecteditem.cells for a column, if the database column is Null or Empty, and I assign that to my web form text control, the control reads "&nbsp;"...
7
by: 一首诗 | last post by:
Is there any simple way to solve this problem?
7
by: John Nagle | last post by:
I've been parsing existing HTML with BeautifulSoup, and occasionally hit content which has something like "Design & Advertising", that is, an "&" instead of an "&amp;". Is there some way I can get...
1
by: zaidalin79 | last post by:
I am in a JavaScript class, and we have to get all of our code to validate at the w3c website... Here is my code, it does what I want it to do which is require the user to enter the name and either...
2
by: bips2008 | last post by:
The code seems to work fine in other browser but in IE it throws this error. This is very urgent for me and any help would be greatly appreciated For your convienence i have posted the code for the...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.