views:

468

answers:

3

Hi,

I am having a javascript array.

addresses = new Array(document.client.cli_Build.value, 
    document.client.cli_Address.value, 
    document.client.cli_City.value, 
    document.client.cli_State.value, 
    document.client.cli_Postcode.value, 
    document.client.cli_Country.value);
document.client.cli_PostalAddress.value = addresses.join(", ");

I have to copy the content of all these array value to the postal address textarea. when i use the above join function, comma has been added for null values. How to remove this extra commas?

Thanks

+1  A: 
document.client.cli_PostalAddress.value = 
    document.client.cli_PostalAddress.value.replace(/(, )+/g,", ");

Or should it be

document.client.cli_PostalAddress.value = 
    document.client.cli_PostalAddress.value
    .replace(/(null, )/g,"").replace(/(, null)/g,"");

??

Victor
add a "g" to do multiple search and replace.
Murali
Wow, you were fast! :)
Victor
this code works like a charm .Thanks for quick reply.document.client.cli_PostalAddress.value=document.client.cli_PostalAddress.value.replace(/(, )+/g,", ");But i am getting a comma added at the end of the address
Krishna Priya
/*Remove null values*/document.client.cli_PostalAddress.value=document.client.cli_PostalAddress.value.replace(/(, )+/g,", ");/* Remove last comma */document.client.cli_PostalAddress.value = document.client.cli_PostalAddress.value.slice(0, -2); /*Remove first comma*/document.client.cli_PostalAddress.value = document.client.cli_PostalAddress.value.substr(1); I used these codes and working fine now. thank u so much for ur help
Krishna Priya
+2  A: 

You can use filter to filter out the null values:

addresses.filter(function(val) { return val !== null; }).join(", ")
Gumbo
Like this better than post processing the joined array elements.
Murali
is there a `filter` in every javascript? I think there is not in some IE
Victor
For the record, I like it better too :), and would do it like that with the help of Underscore.js
Victor
I think you are right, filter is not available in all IE versions.
Murali
@Victor: No, `filter` was specified first in ECMAScript 5 (December 2009). But most modern browsers do have that implemented.
Gumbo
@Victor: A workaround would be either to define that method if missing or using a simple `for` loop to filter the elements out.
Gumbo
@Gumbo: And what for the poor users stuck with a non-modern browser, like IE8?
Victor
@Victor: See my previous comment.
Gumbo
@Gumbo: Dress it any way you want, this code is not useful. Would you always post `undefinedFunction()` as a solution, to then tell people to just "define the method"? That is not very helpful...
Victor
+1  A: 

Underscore is a nice utility library for functional programming and list manipulation:

_.filter(addresses, function(val) { return val !== null; }).join(", ");
Victor