Javascript Replace

Sometime we need to replace the space (‘ ‘) from the any string for validation purpose. Most of the time it need to use validating postcodes. But it is very strange that the replace function of javascript just replace one space.

Suppose we have a string “I    am   a   good      boy”. We write a line for replace all spaces from the string

str = "I am a good boy";
alert(str.replace(' ', '')); // It will give you your expected output.
alert(str.replace(' ', '').length); // It will not give you expected output.

After lot of experiment I solved the problem as follows:


alert(str.split(' ').join('')); // It will give you your expected output.
alert(str.split(' ').join('').length) // It will also give you your expected output.

Thanks

Advertisements

, , ,

  1. #1 by Anjan Bhowmik on July 9, 2011 - 10:18 PM

    Replace works just good like in any other language. if you want to replace ‘a’ with ‘b’, it will replace all ‘a’ with ‘b’ not consecutive ‘a’ like ‘aaaa’ with ‘b’, same applies for spaces, too.

    In your case, you can instead use this –

    str.replace(/\s+/img, ” “);

    This uses regular expression and better than split and join.

    • #2 by Rashedul Islam Sumon on July 10, 2011 - 11:27 PM

      Thanks for your solution, it’s okay with RegEx.

      But JS does not replace all which I didn’t expect 🙂

      • #3 by Anjan Bhowmik on July 11, 2011 - 2:12 AM

        That’s because the first param of the replace function is actually a regex 🙂 so, unless u specify the replace all option in regex, it will always replace the first match found.

  2. #4 by morshed on November 18, 2011 - 8:48 PM

    Nice

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

w

Connecting to %s

%d bloggers like this: