I have strings with extra whitespaces, each time there's more than only one whitespace I'd like it be only one.
Anyone? I tried searching google, but nothing worked for me.
Thanks
I have strings with extra whitespaces, each time there's more than only one whitespace I'd like it be only one.
Anyone? I tried searching google, but nothing worked for me.
Thanks
I presume you're looking to strip spaces from the beginning and/or end of the string (rather than removing all spaces?
If that's the case, you'll need a regex like this:
This will remove all spaces from the beginning or end of the string. If you only want to trim spaces from the end, then the regex would look like this instead:
Hope that helps.
You can augment String to implement these behaviors as methods, as in:
This now enables you to use the following elegant forms to produce the strings you want:
Something like this:
I know I should not necromancy on a subject, but given the details of the question, I usually expand it to mean:
For this, I use code like this (the parenthesis on the first regexp are there just in order to make the code a bit more readable ... regexps can be a pain unless you are familiar with them):
The reason this works is that the methods on String-object return a string object on which you can invoke another method (just like jQuery & some other libraries). Much more compact way to code if you want to execute multiple methods on a single object in succession.
Try this.
the result will be
What happened here is that it will trim the outside spaces first using
trim()
then trim the inside spaces using.replace(/\s+/g, ' ')
.How about this one?
"my test string \t\t with crazy stuff is cool ".replace(/\s{2,9999}|\t/g, ' ')
outputs
"my test string with crazy stuff is cool "
This one gets rid of any tabs as well