This week's book giveaway is in the Jython/Python forum.
We're giving away four copies of Hands On Software Engineering with Python and have Brian Allbey on-line!
See this thread for details.
Win a copy of Hands On Software Engineering with Python this week in the Jython/Python forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Bear Bibeault
  • Knute Snortum
  • Liutauras Vilda
Sheriffs:
  • Tim Cooke
  • Devaka Cooray
  • Paul Clapham
Saloon Keepers:
  • Tim Moores
  • Frits Walraven
  • Ron McLeod
  • Ganesh Patekar
  • salvin francis
Bartenders:
  • Tim Holloway
  • Carey Brown
  • Stephan van Hulst

How to trim spaces between characters of string using javascript  RSS feed

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
I have a function trim(str) which is trimming spaces at begining and after end of string . how to make it to trim spaces between characters of string.
 
author
Posts: 15385
6
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Something like



Would call it like this



I just wrote all that code here, so hopefully there is no typos.

Eric
 
Gold Digger
Posts: 7610
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
For trimAll, I would take special care if the function is applied on a string that contains HTML tags, because the space(s) between attribute values are going to be removed.

Example:
"<table border='0' class='myTable'>".trimAll();
would yield
<tableborder='0'class='myTable'>
which is not good.

Instead, I would declare trimAll as follows:
String.prototype.trimAll = function(replaceStr) {
return this.replace(/\s+/g,replaceStr || "");
}

That way, if replaceStr is provided, the spaces will be replaced by it otherwise, the empty string is used by default.

Now,
"<table border='0' class='myTable'>".trimAll(" ");
correctly yields
<table border='0' class='myTable'>

Of course, if you have left and/or right spaces, you'd have to left/right-trim them as well
 
I want my playground back. Here, I'll give you this tiny ad for it:
RavenDB is an Open Source NoSQL Database that’s fully transactional (ACID) across your database
https://coderanch.com/t/704633/RavenDB-Open-Source-NoSQL-Database
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!