0

I'd like to format a number and remove starting 0s from it. e.g.:
001 => 1

10 => 10

Actually, I have a jQuery method which does the following:

  $('#myelement').text($('#myElement').text()+1);  

When the element's text is 0, the function makes it 01, How can I make it to show 1 using jQuery or javascript?

Thanks.

5 Answers 5

3

what you need:

parseInt($('#myElement').text(), 10) + 1;

what you're asking for:

($('#myElement').text()+1).replace(/^0+/, '');
Sign up to request clarification or add additional context in comments.

5 Comments

Hence the "what you're asking for" predicate. The original question said "I'd like to format a string..."
toFixed returns a string too, but it is aware of rounding rules. For example.
toFixed is on numbers, not strings. If you literally want to remove leading zeros from a string, my answer is correct
I see your point now, please edit your answer a little so I can upvote it.
@cwolvesL: Just What I wanted. Thanks!
2

You can use parseInt("0010", 10).toString(). Ignore toString() if you need the int only.

Comments

1

Assuming you want to increment the value, convert the current text in to a number using unary +:

$('#myelement').text(function(i, v){
    return +v + 1;
});

Comments

0
+"0001" //1

See above! .......

Comments

0
$('#myelement').text(parseInt($('#myElement').text(), 10) + 1);

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.