473,545 Members | 1,987 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

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 47522
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.re place(/ /g,' ');
return null;
}

And your call may be:

var trimmedText = trim( getTextContent( elementReferenc e) ) ;
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, NonBreakingSpac e

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,
NegativeVeryThi nSpace,
NegativeThinSpa ce,
NegativeMediumS pace,
NegativeThickSp ace

<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.re place(/(&nbsp;)|(&ensp ;)|(&emsp;)/g, ' ');
}

</script>

<p onclick="
alert('x'+trim( getTextContent( this))+'x');
">&nbsp;&nbsp;& nbsp;here&nbsp; is&nbsp;the&nbs p;text&nbsp;&nb sp;</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".replac e(/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.or g/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 trimWSCharEntit y(str)
{
return
str.replace(/^(\s|&nbsp;)*/g,"").replace (/(\s|&nbsp;)*$/g,"");
}

Julian

Nov 7 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

23
5649
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 reduced my form request to a simple text string entry, instead of my desired optional parameters. As i have been stuck with a single unfathomable...
14
24065
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 convert n = "" # init new string for i in str: if i in chr: # if special character in str n+='\\' # append...
13
6331
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 well as Page Valet indicate it is valid. The page is being served with the proper MIME type of "application/xhtml+xml". Unfortunately, Firefox...
5
11150
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 text. Its not doing what I am trying to do. The text shows up as "&ampMyValue"
0
2551
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;" instead of a blank. Never had this happen before, but I am now using Asp.Net 2.0. Ideas please?
7
49838
by: 一首诗 | last post by:
Is there any simple way to solve this problem?
7
4599
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 BeautifulSoup to clean those up? There are various parsing options related to "&" handling, but none of them seem to do quite the right thing. If I...
1
3193
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 the address of the email address, but when I try to validate it through w3c, I get the following errors... Can anyone help? <!DOCTYPE html...
2
4285
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 file. The portion that is not working is the star rating part <?php session_start(); include_once('includes/host_conf.php');...
0
7475
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7664
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. ...
0
7918
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7436
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For...
0
7766
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the...
0
5981
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then...
1
5341
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes...
0
3446
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
0
715
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating...

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.