Win a copy of Java Challengers this week in the Java in General 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 Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Paul Clapham
  • Ron McLeod
  • paul wheaton
  • Devaka Cooray
Sheriffs:
  • Jeanne Boyarsky
  • Tim Cooke
  • Liutauras Vilda
Saloon Keepers:
  • Tim Moores
  • Tim Holloway
  • Stephan van Hulst
  • Carey Brown
  • Piet Souris
Bartenders:
  • salvin francis
  • Mikalai Zaikin
  • Himai Minh

How to trim spaces between characters of string using javascript

 
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Author & Gold Digger
Posts: 7617
6
IntelliJ IDE Java
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
Message for you sir! I think it is a tiny ad:
Thread Boost feature
https://coderanch.com/t/674455/Thread-Boost-feature
reply
    Bookmark Topic Watch Topic
  • New Topic