473,581 Members | 3,046 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

How-to: JavaScript trim() and normalize-space() functions

Hi all.

Just wanted to share two handy RegEx expressions to strips leading and
trailing white-space from a string, and to replace all repeated spaces,
newlines and tabs with a single space.

* JavaScript example:

String.prototyp e.trim = function() {
// Strip leading and trailing white-space
return this.replace(/^\s*|\s*$/g, "");
}

String.prototyp e.normalize_spa ce = function() {
// Replace repeated spaces, newlines and tabs with a single space
return this.replace(/^\s*|\s(?=\s)|\ s*$/g, "");
}

" one \t two three \n ".trim(); // --> "one \t two three"
" one \t two three \n ".normalize_spa ce(); // --> "one two three"
Enjoy,
Alex Vassiliev (New Zealand)

Sep 29 '05 #1
5 33289
you will not even get there on an OS handling basis
-----------

you are a lonely motherf*er

"Alex Vassiliev" <al************ @gmail.com> wrote in message
news:11******** **************@ g47g2000cwa.goo glegroups.com.. .
Hi all.

Just wanted to share two handy RegEx expressions to strips leading and
trailing white-space from a string, and to replace all repeated spaces,
newlines and tabs with a single space.

* JavaScript example:

String.prototyp e.trim = function() {
// Strip leading and trailing white-space
return this.replace(/^\s*|\s*$/g, "");
}

String.prototyp e.normalize_spa ce = function() {
// Replace repeated spaces, newlines and tabs with a single space
return this.replace(/^\s*|\s(?=\s)|\ s*$/g, "");
}

" one \t two three \n ".trim(); // --> "one \t two three"
" one \t two three \n ".normalize_spa ce(); // --> "one two three"
Enjoy,
Alex Vassiliev (New Zealand)


Sep 29 '05 #2
Alex Vassiliev wrote on 29 sep 2005 in comp.lang.javas cript:
String.prototyp e.trim = function() {
// Strip leading and trailing white-space
return this.replace(/^\s*|\s*$/g, "");
}


Nice one, Alex.

To have them all [the recurses are a variation]:

<script type='text/javascript'>

String.prototyp e.trim = function(x) {
if (x=='left')
return this.replace(/^\s*/,'');
if (x=='right')
return this.replace(/\s*$/,'');
if (x=='normalize' )
return this.replace(/\s{2,}/g,' ').trim();

return this.trim('left ').trim('right' );
}

test = ' \n blah \n blah \n '
alert('x'+test+ 'x')
alert('x'+test. trim('left')+'x ')
alert('x'+test. trim('right')+' x')
alert('x'+test. trim('both')+'x ')
alert('x'+test. trim('normalize ')+'x')
alert('x'+test. trim()+'x')

</script>

--
Evertjan.
The Netherlands.
(Replace all crosses with dots in my emailaddress)

Sep 29 '05 #3
On 29/09/2005 09:08, commercial wrote:

[Corrected top-post]
"Alex Vassiliev" <al************ @gmail.com> wrote in message
news:11******** **************@ g47g2000cwa.goo glegroups.com.. .
[snip]
String.prototyp e.trim = function() {
// Strip leading and trailing white-space
return this.replace(/^\s*|\s*$/g, "");
}
Incidentally, this already exists in the group FAQ
(<URL:http://www.jibbering.c om/faq/#FAQ4_16>).
String.prototyp e.normalize_spa ce = function() {
// Replace repeated spaces, newlines and tabs with a single space
return this.replace(/^\s*|\s(?=\s)|\ s*$/g, "");
}


Useful as they are, lookahead assertions aren't available in all
browsers. Unless you're happy compromising execution by raising syntax
errors, they should be avoided:

String.prototyp e.normalise = function() {
return this.replace(/^\s+|\s+$/g, '').replace(/\s{2,}/g, ' ');
};

One thing that needs consideration is behaviour with mixed whitespace.
Your regular expression saves the last whitespace character in a
sequence. So, an earlier character could have been a new line, but might
be replaced by a space. Conversely, the sequence could have been all
spaces with the exception of a final new line, and it's that character
that is saved.

By comparison, the alternative above would always replace a whitespace
sequence with a single space.

[snip]
you will not even get there on an OS handling basis
If you do insist on posting, will you at least make sense. And don't
top-post.
you are a lonely motherf*er


However, if you're going to behave like that, could you refrain from
posting at all.

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Sep 29 '05 #4
>One thing that needs consideration is behaviour with mixed whitespace.
Your regular expression saves the last whitespace character in a
sequence. So, an earlier character could have been a new line, but might
be replaced by a space. Conversely, the sequence could have been all
spaces with the exception of a final new line, and it's that character
that is saved.


Good one! I haven't thought about that... It is definitely a bug.
Thank you Michael

Sep 29 '05 #5
JRS: In article <11************ **********@g47g 2000cwa.googleg roups.com>
, dated Wed, 28 Sep 2005 18:28:42, seen in news:comp.lang. javascript,
Alex Vassiliev <al************ @gmail.com> posted :
String.prototyp e.normalize_spa ce = function() {
// Replace repeated spaces, newlines and tabs with a single
space
return this.replace(/^\s*|\s(?=\s)|\ s*$/g, "");
}


That won't work for me.

Otherwise, I might have used it in my presently-crude paragraph-packer.

I much dislike reading articles,
usually
press statements or similar, in
which the
layout is like this forced
example
(but wider).

So I added a "Pack" button to <URL:http://www.merlyn.demon.co.uk/js-
quick.htm>; its code is still crude.

--
© John Stockton, Surrey, UK. ?@merlyn.demon. co.uk Turnpike v4.00 IE 4 ©
<URL:http://www.jibbering.c om/faq/> JL/RC: FAQ of news:comp.lang. javascript
<URL:http://www.merlyn.demo n.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demo n.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Sep 30 '05 #6

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

Similar topics

1
3337
by: Matt | last post by:
My problem is when the user click the submit button, it will launch another new window for the request page. I want to confirm we cannot use JavaScript open window functions to open a request page? The following page2.asp won't output the value entered in page1.asp. However, if we do <form action="page2.asp" method="get" target="_blank">, then...
11
4727
by: Reply Via Newsgroup | last post by:
Folks, In PHP and some other scripting languages, one has trim() - It removes newline, tabs and blank spaces that might prefix, or suffix a string. Can someone tell me how I can do this in javascript? Much appreciated, randell d.
10
2064
by: Emre Sevinc | last post by:
Take a look at the following snippet: <html> <head> <script> function add(elementId) { var container = document.getElementById(elementId); for (var i = 0; i < 10; i++) { var elt = document.createElement('div'); elt.innerHTML = "" + i;
1
1432
by: Liam | last post by:
We recently decided to go from cookieless to cookies, changing web.config to read cookieless=false. Since making that change, I've noticed that javascript functions kept in included libraries are not available. They'd been working for over a year. The libraries are included in the <HEAD> of the HTML page: <script language="javascript"...
1
2378
by: rapin | last post by:
How do you make javascript’s string functions (like toUpperCase() or substr()) run under SpiderMonkey to handle multi-byte characters. For example: var strTest = "ørnen på"; var strWork = strTest.toUpperCase(); print( strWork ); The result is øRNEN På
3
4057
by: Shailesh Humbad | last post by:
I compiled this article on trim functions for Javascript: Javascript Trim LTrim and RTrim Functions http://www.somacon.com/p355.php If you have any comments, please let me know. Thanks, Shailesh
31
2885
by: rkk | last post by:
Hi, I've written a small trim function to trim away the whitespaces in a given string. It works well with solaris forte cc compiler, but on mingw/cygwin gcc it isn't. Here is the code: char *trim(char *s) { char *begin,*end; begin = s;
1
25645
pbmods
by: pbmods | last post by:
VARIABLE SCOPE IN JAVASCRIPT LEVEL: BEGINNER/INTERMEDIATE (INTERMEDIATE STUFF IN ) PREREQS: VARIABLES First off, what the heck is 'scope' (the kind that doesn't help kill the germs that cause bad breath)? Scope describes the context in which a variable can be used. For example, if a variable's scope is a certain function, then that...
7
2912
by: Henri | last post by:
Hello, any idea why a regexp-based trim function would work fine in firefox but not in ie? code is String.prototype.trim = function() { re = /\s*$/g; return this.replace(re, "");
0
8312
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
7920
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
8183
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...
1
5685
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
5366
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3809
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in...
0
3835
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1413
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1147
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.