473,388 Members | 1,256 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,388 software developers and data experts.

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.prototype.trim = function() {
// Strip leading and trailing white-space
return this.replace(/^\s*|\s*$/g, "");
}

String.prototype.normalize_space = 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_space(); // --> "one two three"
Enjoy,
Alex Vassiliev (New Zealand)

Sep 29 '05 #1
5 33247
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.googlegr oups.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.prototype.trim = function() {
// Strip leading and trailing white-space
return this.replace(/^\s*|\s*$/g, "");
}

String.prototype.normalize_space = 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_space(); // --> "one two three"
Enjoy,
Alex Vassiliev (New Zealand)


Sep 29 '05 #2
Alex Vassiliev wrote on 29 sep 2005 in comp.lang.javascript:
String.prototype.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.prototype.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.googlegr oups.com...
[snip]
String.prototype.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.com/faq/#FAQ4_16>).
String.prototype.normalize_space = 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.prototype.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**********************@g47g2000cwa.googlegroups .com>
, dated Wed, 28 Sep 2005 18:28:42, seen in news:comp.lang.javascript,
Alex Vassiliev <al************@gmail.com> posted :
String.prototype.normalize_space = 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.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.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
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?...
11
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...
10
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 =...
1
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...
1
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 ...
3
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,...
31
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...
1
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...
7
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
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: 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
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
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,...
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,...

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.