0

So I have this

var str=document.getElementById('elem').innerHTML;
str=parseInt(str)+1;

<span id="elem">1,500</span>

and I can't get it to take the entire number and add one (+1) to the number without taking comma off. Can you suggest something?

4
  • try str=parseInt(str.replace(',','')) + 1 Commented Oct 5, 2014 at 21:16
  • stackoverflow.com/questions/9277948/… Commented Oct 5, 2014 at 21:16
  • +'1,500'.replace(',', '') + 1 Commented Oct 5, 2014 at 21:17
  • I can understand that I need to replace a comma. I was asking how to do it. Commented Oct 6, 2014 at 9:22

1 Answer 1

2

Remove the commas by replacing them with an empty string, then you can parse the string.

Remember the second parameter in the parseInt method that specifies the base, so that it doesn't use base 8 for zero padded values.

var num = parseInt(str.replace(/,/g, ''), 10) + 1;

If you want to put the changed number back formatted with commas, you can use:

var s = num.toString();
for (var i = s.length - 3; i > 0; i -= 3) {
  s = s.substr(0, i) + ',' + s.substr(i);
}
document.getElementById('elem').innerHTML = s;
Sign up to request clarification or add additional context in comments.

Comments

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.