JSRookie
JSRookie

Reputation: 53

Javascript array manipulation

I want to create string (delimited by pipe '||') from the contents of an array. I want to remover $ from the item and add || between two items. But I don't want to add || after the last array item. Easiest way to do this?

This is what I have done so far:

var array = ["$db1", "$db2", "$db3", "$db4"];

var dbs = "";

for(var i = 0; i < array.length, i++){
    if(array[i].charAt(0) == "$"){
        dbs += array[i].replace("$","") + "||";
        alert(dbs);
    }
}

Upvotes: 1

Views: 1884

Answers (5)

scrappedcola
scrappedcola

Reputation: 10572

var array = ["$db1", "$db2", "$db3", "$db4"];
var arrStr = array.join("||");
var dbs = arrStr.replace(/\$/g, "");

Grr sorry forgot to add the \g switch to replace all.

Upvotes: 0

Amadan
Amadan

Reputation: 198324

array.join('||').replace(/(^|(\|\|))\$/g, '$1');

Join with ||, then annihilate any $ following either the beginning of the string or the separator. Works as long as your strings do not contain || (in which case, I think you have bigger problems).

Upvotes: 0

Šime Vidas
Šime Vidas

Reputation: 185913

Here you go:

array.join('||').replace(/\$/g,'')

Live demo: http://jsfiddle.net/ZrgFV/

Upvotes: 7

SBSTP
SBSTP

Reputation: 3639

var dbs = array.join('||').replace(/$/gi, '');

This.

Upvotes: -2

Ry-
Ry-

Reputation: 224904

var array = ["$db1", "$db2", "$db3", "$db4"];
var dbs = array.map(function(x) { return x.substring(1); }).join('||');

It requires the relatively new Array.map, so also include:

if(![].map) Array.prototype.map = function(f) {
    var r = [], i = 0;
    for(; i < this.length; i++) r.push(f(this[i]));
    return r;
};

I took it that you meant "remove a leading $" because they're all at the beginning. If not, use:

var array = ["$db1", "$db2", "$db3", "$db4"];
var dbs = array.join('||').replace(/\$/g, '');

Upvotes: 0

Related Questions