1

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

7

Here you go:

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

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

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks for the quick reply! Can you explain the pattern for replace?
@JSRookie Read here. In short, /\$/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).
0
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

Your Array.prototype.map won't do anything but copy the array, I think you meant to r.push(f(this[i]))
0
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

0
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

This fails miserably with more than one item. Did you actually test it? .replace with a string only replaces the first occurrence of the string.
without a global regex your last line will only replace the first $
Yea i saw that and not it's fixed
Now it does. Notifying @tomfumb?
-2
var dbs = array.join('||').replace(/$/gi, '');

This.

2 Comments

case-insensitive seems a little redundant here!
$ is a special regex character and i is unnecessary.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.