Click here to Skip to main content
14,924,198 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
See the snippet of javascript code below.

I need to not only trim, but remove all interior spaces between words/letters.

So the string " dog cat bird "

Thanks in advance.

if($.trim($('#question{QID} input:text:eq(0)').val()) == '') {

What I have tried:

if($.trim($(str.replace('#question{QID} input:text:eq(0)')).val()) == '') {
Updated 6-Dec-19 1:37am

Use the javascript string replace method. No need to use trim as well.

newstring = oldstring.replace(/' '/g, '');

Update: need "g" flag to replace all, not just the first.
Afzaal Ahmad Zeeshan 29-Nov-19 0:18am
Just curious, what is the difference in simply doing this?

oldstring.replace(" ", "");
Peter_in_2780 29-Nov-19 0:29am
That will replace only the first occurrence.
Maciej Los 29-Nov-19 3:40am
If you just want to test whether a string contains any non-whitespace characters, you don't need to create a new string at all:
if (!(/[^\s]/).test($('#question{QID} input:text:eq(0)').val())) {
    // The value only contains whitespace.
Maciej Los 29-Nov-19 8:14am
I'm curious of your suggestion in case when value contains non-whitespace characters...
Richard Deeming 29-Nov-19 8:22am
The OP is testing whether removing all whitespace characters from the string results in an empty string. Which is another way of testing whether the string contains non-whitespace characters.

I'm just slightly annoyed that I had to use a double negative to match the semantics of the original test. :)
Maciej Los 29-Nov-19 8:42am
I forgot to mention, that... 5ed!
Instead of using trim() , its easy with replace() which removes spaces between words and also the empty spaces before words.

var b=" In d ia "

console.log(b.replace(/ /g,""))


Alternate solution:

Richard Deeming 6-Dec-19 8:35am
Already mentioned in Solution 1.
CHill60 6-Dec-19 9:08am
Whilst I commend your desire to help I advise you to take more care - check previous solutions posted and make sure you are not just repeating what has already been said. Try to bring something new to the thread
[no name] 7-Dec-19 0:55am
can u please execute and check your answer ,so called solution 1 and also even mine, so that you can know the difference.

thank you .

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900