I have a string:
var string=“2,4,6,1,2,2”;
First I want to get ride of the commas:
var comma=string.replace(/,/g,“”);
Then I want to pick out all number 2:
var twos=comma.match(/2/g);
But this gives me: 2,2,2
The commas are still there? Why?
I have a string:
var string=“2,4,6,1,2,2”;
First I want to get ride of the commas:
var comma=string.replace(/,/g,“”);
Then I want to pick out all number 2:
var twos=comma.match(/2/g);
But this gives me: 2,2,2
The commas are still there? Why?
You are returning an array, which is converted by default to a comma separated string.
twos=comma.match(/2/g).join(‘’)//join with no separator
or even
“2,4,6,1,2,2”.match(/2/g).join(‘’);
Thank you very much!
After doing that I get 222. How do I add the numbers? Instead of 222 I want to add them to get six.
var twos=“2,4,6,1,2,2”.match(/2/g),total=0;
while(twos.length)total+=(+twos.shift());
alert(total)
You probably have more work to do- this will match the 2s in ‘12’ and ‘22’ and ‘1.25’ and give you an incorrect result.
Thank you again! Have a nice day!
I have a form, you click a button and a series av random numbers gets created. I put the numbers in a array.
I call this var numbers= new Array();
numbers[0]=number1;
numbers[1]=number2;
etc.
Let’s say clickin the button gives me this: 6,2,6,6,6
I want to pick out the sixes and add them. I have tried this:
var total=0;
var six=numbers.match(/6/g);
while(numbers.length),total+=(+numbers.shift());
document.getElementById(“div1”).innerHTML=total;
But it does not work. What am I doing wrong? If I replace var six=numbers.match(/6/g); with six=“6,2,6,6,6.match(/6/g);” I dont get this problem, but I want to fetch the values from a variable.
Sorry, got that wrong. It should be like this:
var total=0;
var six=numbers.match(/6/g);
while(six.length),total+=(+six.shift());
document.getElementById(“div1”).innerHTML=total;