Forum Moderators: open

Message Too Old, No Replies

Help with this array please

         

Champak

9:49 am on Feb 22, 2007 (gmt 0)

10+ Year Member



I need to make the following php script a javascript if it is possible. 1/ It takes an array and puts a comma between each of the words that it outputs if it exists in the array. So that blank quotation would not be in the output string and the extra commas around it will not show up at all.
2/ It does not put a comma after the last word.

string = join(", ", array_filter(array_values(["Cat", "", "Horse", "Dog"])))

StupidScript

9:42 pm on Feb 22, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



var arry=new Array("Cat", "", "Horse", "Dog");
var string=arry.join();
string=string.replace(/,,/g,",");

Champak

4:48 pm on Feb 23, 2007 (gmt 0)

10+ Year Member



Thanks, that almost works, but it still leaves a few commas as the array expands beyond the 4 things I originally had as an example. I don't know how the amount of variables I have in the array exactly affects how your script works to adjust it. So to clarify a little more, there are actually 9 things/variables that may or may not go into the array. And also if you could, tell me how to expand it if I need to put more things in.

Also I need to delete leading commas. Sometimes the first few variables might not exist but the commas show up.

So it would look like this:
var arry=new Array("var1", "var2", "var3", "var4", "var4", "var5", "var6", "var7", "var8", "var9");
var string=arry.join();
string=string.replace(/,,/g,",");

And any one or all of those variables may or may not exist.

Thanks

[edited by: Champak at 5:01 pm (utc) on Feb. 23, 2007]

cmarshall

6:44 pm on Feb 23, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



string=string.replace(/,,/g,",");
string=string.replace(/^,¦,$/g,"");

A real Regex whiz could do it in one statement.

StupidScript

6:49 pm on Feb 23, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



The regular expression (
/,,/g
) would match any to consecutive commas, i.e. where a middle variable might be missing. It doesn't detect leading or trailing commas, as you noted. Here's a more complete script to handle leading/trailing commas and instances where there are several empty values that result in multiple commas:

//get array values (left some vals blank for demo)
var arry=new Array("", "var2", "", "", "var4", "var5", "", "var7", "var8", "");

//make comma-separated string from array vals
var string=arry.join();

//strip leading comma
string=string.replace(/^,/,"");

//strip trailing comma
string=string.replace(/,$/,"");

//replace double commas with single comma
//the 'g' indicates 'global replace' (all instances)
string=string.replace(/,,/g,",");

//function to fix extra commas if simple replace doesn't get them all
function commas() { string=string.replace(/,,/g,","); }

//check for remaining multiple commas and reprocess
//the routine only checks for double commas
//keep doing it until no more double commas
if (string.indexOf(",,")!=-1) { commas(); }

//all cleaned up, so view result
document.write(string);

There may be a more elegant way to handle this, but there're almost no performance issues.
<edit>
Along the lines of what cmarshall slipped in there while I was typing! :)
</edit>

Also, it doesn't matter how many array elements there are/aren't.

[edited by: StupidScript at 6:53 pm (utc) on Feb. 23, 2007]

cmarshall

7:20 pm on Feb 23, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Let's see if I'm a real regex whiz:

string=string.replace(/,,/g,",");
string=string.replace(/^,¦,$/g,"");

A real Regex whiz could do it in one statement.

Ahhh... Sort of:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>Test</title>
<script type="text/javascript">
// <![CDATA[
function show_result(in_string){
alert((in_string.replace(/,,/g,",")).replace(/^,¦,$/g,""));
}
// ]]>
</script>
</head>
<body>
<div>
<form action="#" onsubmit="show_result(getElementById('test').value);return false"><div>
<label for="test">Enter a String to Parse:</label> <input type="text" id="test" />
<input type="submit" onclick="show_result(getElementById('test').value);return false" />
</div></form>
</div>
</body>
</html>

Remember that WebmasterWorld likes to nuke the "¦" character into that two-part character. You need to replace it with the regular "or-bar."

Champak

8:11 pm on Feb 23, 2007 (gmt 0)

10+ Year Member



cmarshall, I don't understand how to use what you have.

StupidScript, It works a little better, but not there yet. Try the following things and see what I mean:
("var1", "", "var3", "", "", "", "var7", "", "") -- leaves trailing comma
("", "var2", "", "var4", "var5", "", "", "", "") -- leaves trailing comma
("", "", "", "var4", "var5", "", "", "var8", "") -- leaves leading comma
("", "", "", "", "var5", "", "", "var8", "var9") -- leaves leading comma
("", "", "", "var4", "var5", "var6", "", "", "") -- leaves leading and trailing comma

Also, if there is one value alone, two commas always show up like ",dog," ",,dog" or "dog,,".

There are other combinations, but you can see what I mean.

[edited by: Champak at 8:14 pm (utc) on Feb. 23, 2007]

cmarshall

8:17 pm on Feb 23, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This is the magic part:

in_string.replace(/,,/g,",")).replace(/^,¦,$/g,"")

Where "in_string" is your string to clean.

If you set

in_string = in_string.replace(/,,/g,",")).replace(/^,¦,$/g,"");
, it will clean the commas as stated.

StupidScript

8:25 pm on Feb 23, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Okay then, we'll just check and fix all three conditions: leading comma, trailing comma, multiple commas

//get array values (left some vals blank for demo)
var arry=new Array("", "", "", "var4", "var5", "var6", "", "", "");
//make comma-separated string
var string=arry.join();
//initial cleaning (as before)
string=string.replace(/^,/,"");
string=string.replace(/,$/,"");
string=string.replace(/,,/g,",");
//function to loop until clean
function commas() {
string=string.replace(/^,/,"");
string=string.replace(/,$/,"");
string=string.replace(/,,/g,",");
}
//check for more issues and reprocess
if (string.indexOf(",,")!=-1 ¦¦ string.substring(0,1)=="," ¦¦ string.substring(-1)==",") {
commas();
}
//view result
document.write(string);

Getting close ... I can feel it! :)

Champak

9:26 pm on Feb 23, 2007 (gmt 0)

10+ Year Member



cmarshall, it does not work at all, unless I'm doing something wrong.
var arry=new Array("", "", "", "var4", "var4", "var5", "", "", "var8", "");
var string=arry.join();
in_string=string.replace(/,,/g,",").replace(/^,¦,$/g,"");
document.write(in_string);

StupidScript, I'm feeling it too :), the following is still kicking in extra commas:
("", "", "", "", "var5", "", "", "var8", "var9") -- leaves leading comma
("", "var2", "", "var4", "var5", "", "", "", "") -- leaves trailing comma

Just a little more:)

Thank both of you so far.

StupidScript

10:25 pm on Feb 23, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



DOH! Wrong order ...

//get array values (left some vals blank for demo)
var arry=new Array("", "", "", "", "var5", "", "", "var8", "var9");
//make comma-separated string
var string=arry.join();
//initial cleaning (as before)
string=string.replace(/,,/g,",");
string=string.replace(/^,/,"");
string=string.replace(/,$/,"");
//function to loop until clean
function commas() {
string=string.replace(/,,/g,",");
string=string.replace(/^,/,"");
string=string.replace(/,$/,"");
}
//check for more issues and reprocess
if (string.indexOf(",,")!=-1 ¦¦ string.substr(0,1)=="," ¦¦ string.substr(-1)==",") {
commas();
}
//view result
document.write(string);

Check for double commas FIRST ... THEN clean off head and tail. Sheesh! ;)

cmarshall

10:55 pm on Feb 23, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Did you replace the "¦" character? Remember that WebmasterWorld substitutes a non-standard character in place of the "OR-bar." You need a standard "OR-bar" for the Regex to work.

I just tested it out again, and it worked on every browser I tried.

There is one string that I was able to throw at it that confused it a bit:

",a,b,c,d,,f,g,,, ,h,"

Changing the regex to this

in_string.replace(/(,\s*,)+/g,",")).replace(/^,¦,$/g,"")

addresses that, but this is a kludge. There is almost certainly a more elegant way to do it.

Otherwise, it works fine.

Champak

2:47 am on Feb 24, 2007 (gmt 0)

10+ Year Member



cmarshall, yes I did replace it, but it still just doesn't work for me, you see the example that I placed in the previous post...with the exception that I replaced the bar. So if that is correct, that is exactly what I did, and also with the new script you provided.

StupidScript, you are a genius, we are finally there:) thank you very much, it works like a charm. One last thing if it is possible...no biggie, I didn't realize before, but I am trying to add in a space after the comma if one is put in but can't seem to do it. I leave an open space after the comma like "string=string.replace(/,,/g,", ");" I also put "&nbsp;" after the comma, but no luck. Is this possible?

Thanks again for all your help.

cmarshall

3:35 am on Feb 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



This works:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN"
"http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
<title>
Test
</title>
</head>
<body>
<div>
<script type="text/javascript">
// <![CDATA[
var arry=new Array("", "", "", "var4", "var4", "var5", "", "", "var8", "");
var string=arry.join(",");
var in_string=(string.replace(/(\s*,\s*)+/g,",")).replace(/^,¦,$/g,"");
document.writeln(string+"<br />");
document.write(in_string);
// ]]>
</script>
</div>
</body>
</html>

StupidScript

4:12 am on Feb 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Wait until all of the replacements are done:

//get array values (left some vals blank for demo)
var arry=new Array("", "", "", "", "var5", "", "", "var8", "var9");
//make comma-separated string
var string=arry.join();
//initial cleaning (as before)
string=string.replace(/,,/g,",");
string=string.replace(/^,/,"");
string=string.replace(/,$/,"");
//function to loop until clean
function commas() {
string=string.replace(/,,/g,",");
string=string.replace(/^,/,"");
string=string.replace(/,$/,"");
}
//check for more issues and reprocess
if (string.indexOf(",,")!=-1 ¦¦ string.substr(0,1)=="," ¦¦ string.substr(-1)==",") {
commas();
}
string=string.replace(/,/g,", ");
//view result
document.write(string);

Enjoy!

<edit>
I gotta think that cmarshall's approach is more elegant, plus the idea that a var could contain an empty space is intriguing, so there're some modifications that could/should be made ... not to mention the condition that some vars might actually contain commas, in a normal string ...

Try the bold line without the

g
to see what it does.
</edit>

[edited by: StupidScript at 4:42 am (utc) on Feb. 24, 2007]

cmarshall

4:48 am on Feb 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Well, a regex will do marvelous things, but they are a real b%$ch to write properly.

If you substitute the comma for a tab in the join(), you get more flexibility.

This will give you your space after the comma:

var arry=new Array("", "", "", "var4", "var4", "var5", "", "", "var8", "");
var string=arry.join("\t");
var in_string=(string.replace(/(\s*\t\s*)+/g,", ")).replace(/^\s*[\t¦,]¦[\t¦,]\s*$/g,"");
document.writeln(string+"<br />");
document.write(in_string);

StupidScript

5:02 am on Feb 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You madman! :)

appi2

6:27 am on Feb 24, 2007 (gmt 0)

10+ Year Member



Do cmmarshals, but I'll post this just cos I bothered.

<script type="text/JavaScript">
var arry=new Array("", "", "", "var4", "var5", "", "", "var8", "var9","");
var string=""
for(var i = 0; i < arry.length; i++) {
if (arry[i]!= "") {
string+=arry[i]+", ";
}
}
string=string.replace(/, $/g,""); //looks for comma+space from the end of the string and deletes.
document.write(string);
</script>

cmarshall

2:10 pm on Feb 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



You madman! :)

Mais oui, Josephine. ;)

Champak

8:27 pm on Feb 24, 2007 (gmt 0)

10+ Year Member



cmarshall, that works perfect now thanks. It was missing the opening "(" in the previous versions, that's why it wasn't working...thanks for your persistence.

StupidScript, thanks for all of your help.

cmarshall

8:55 pm on Feb 24, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Glad it worked out.

The problem with JavaScript is that it's so quiet when it hits an error. That's why I use FF with the DOM Inspector and the Web Developer Toolbar.