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);
}
}
Here you go:
array.join('||').replace(/\$/g,'')
Live demo: http://jsfiddle.net/ZrgFV/
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, '');
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).
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.
var dbs = array.join('||').replace(/$/gi, '');
This.
精彩评论