Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Mike Lewis on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Adding a character to string created with an array 1

Status
Not open for further replies.

gabrielAllen

Programmer
Feb 14, 2001
19
0
0
US
I have an array of address information - 7 elements. I am currently use join() to string these values together, but need to add a "," after each value if it is not null. Also, I only need this for the interior of the string. The last element does not need a ",".

Example: Address1, City, State, Zip
 
the join command will automatically add a separator character and the default if none is specified is to add a comma. Like this:

var arJoin = new Array("11", "12", "13", "14", 15)
var myval = arJoin.join();
alert(myval);

You can specify a different separator like this:

var myval = arJoin.join('|');


At my age I still learn something new every day, but I forget two others.
 
Thanks for the repsonse. What would you do in this scenario:

var arJoin = new Array("11", "", "13", "14", 15)
var myval = arJoin.join();
alert(myval);

If I were to use a "," as the separator, my output would look like this: "11,,13,14,15"

How can I remove the extra separator if the value is null?
 
[tt]//a being the given array
var s=a.join(",").replace(/(,)+/g,","); //the answer
[/tt]
 
Thanks! I tried this, but I can't seem to get it to work. Here is an example of what I am using:

var newAddress = newAddressList.join(", ").replace(/(,)+/g,", ");


It's not working for me.
 
tsuji's method looks good above.
I would have suggested looping through the array to filter out empty values but I think an inline replace is more efficient.

Code:
var arJoin = new Array("11", "", "13", "14", 15)

for (var x=0; x<arJoin.length; x++) {
  if (arJoin[x] == '') {
    arJoin.splice(x,1);
  }
}
var myval = arJoin.join();
alert(myval);

At my age I still learn something new every day, but I forget two others.
 
>[tt] newAddressList.join(",[highlight] [/highlight]")[/tt]
If you want a space after, that is not exactly same question. Have to do this instead.
[tt] var newAddress = newAddressList.join(", ").replace(/(,( ){1})+/g,", ");[/tt]
 
Thanks all! This seems to work, but what if the last value in the array is null: "(11,12,'',14,'')?
 
That's a legitimate followup. Try this.

[tt] newAddressList=newAddressList.join(", ").replace(/^(,( ){1})+/g,"").replace(/(,( ){1})+/g,", ").replace(/(,( ){1})+$/g,"");[/tt]

But I just get too fed to spend more time to make it more concise. Maybe it's already is.
 
Again, thank you! I relly appreciate the time and effort from both of you. Thanks!
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top