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);
}
}
5 Answers 5
2 Comments
/\$/g is a regular expression which matches all $ characters in the string. The second argument is an empty string ('') which means that all $ characters are replaced by an empty string (= they are deleted from the string).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, '');
1 Comment
r.push(f(this[i]))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).
Comments
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.
4 Comments
.replace with a string only replaces the first occurrence of the string.var dbs = array.join('||').replace(/$/gi, '');
This.
2 Comments
$ is a special regex character and i is unnecessary.